how to read and edit existing pptx using Docx4j? - java

I am using the following code to iterate over existing pptx, but how can I edit (replace text or image) in specific slide.
Example in documentation
String inputfilepath = "C:/tmp/template.pptx";
PresentationMLPackage presentationMLPackage =
(PresentationMLPackage)OpcPackage.load(new java.io.File(inputfilepath));
for (int i=0 ; i<presentationMLPackage.getMainPresentationPart().getSlideCount(); i++) {
SlidePart slidePart = presentationMLPackage.getMainPresentationPart().getSlide(i);
SlideLayoutPart slideLayoutPart = slidePart.getSlideLayoutPart();
//System.out.println(slp.getSourceRelationships().get(0).getTarget());
System.out.println(slidePart.getPartName().getName());
String layoutName = slideLayoutPart.getJaxbElement().getCSld().getName();
System.out.println("layout: " + slideLayoutPart.getPartName().getName() + " with cSld/#name='" + layoutName + "'");
System.out.println("Master: " + slideLayoutPart.getSlideMasterPart().getPartName().getName());
}

I have done many researches on office files like docx,xlsx,ppt
I would like to suggest you one thing
Once you open your file with zip/rar you will find its internal file structure
Files
_rels
docProps
ppt
[Content_types].xml
these folders contain files are usually xml
PPt and move to slides inside slide
there will be xml files names slide1..2..3.etc
these files have every text you type in your ppt.
Replace Xml file with your content
using the java coding and place it back into zip file.
Thats it.
Its working 100% i have implemented it many times.
**summary:**
In java code just try this
1.Rename your file extension from pptx to zip
2.extract path ppt\slides\[yourslide].xml
3.do your content replacement for the extracted xml file.
4.Place it back into zip
5.rename the file extension to pptx
That is it enjoy!!!
regards,
Kishan.c.s

Related

Read the data from TXT file inside Zip File without extracting the contents in Matlab

I have tab delimited ascii data in txt files which are zip compressed (and the zip may or may not contain other files). I would like to read this data into a matrix without uncompressing the zip files.
There were a few similar #matlab / #java posts earlier:
Read the data of CSV file inside Zip File without extracting the contents in Matlab
Extracting specific file from zip in matlab
Read Content from Files which are inside Zip file
I have gotten this far thanks to the above - I can identify the .txt inside the zip, but don't know how to actually read its contents. First example:
zipFilename = 'example.zip';
zipJavaFile = java.io.File(zipFilename);
zipFile=org.apache.tools.zip.ZipFile(zipJavaFile);
entries=zipFile.getEntries;
cnt=1;
while entries.hasMoreElements
tempObj=entries.nextElement;
file{cnt,1}=tempObj.getName.toCharArray';
cnt=cnt+1;
end
ind=regexp(file,'$*.xml$');
ind=find(~cellfun(#isempty,ind));
file=file(ind);
file = cellfun(#(x) fullfile('.',x),file,'UniformOutput',false);
% Now Operate Any thing on File.
zipFile.close
HOWEVER, I found no example as to how to "operate anything on file". I can extract the path within the zip file, but don't know how to actually read the contents of this txt file. (I wish to directly read its contents into memory -- a matrix --, without extraction, if possible.)
The other example is
zipFilename = 'example.zip';
zipFile = org.apache.tools.zip.ZipFile(zipFilename);
entries = zipFile.getEntries;
while entries.hasMoreElements
entry = entries.nextElement;
entryName = char(entry.getName);
[~,~,ext] = fileparts(entryName);
if strcmp(ext,'.txt')
inputStream = zipFile.getInputStream(entry);
%Read the contents of the file
inputStream.close;
end
end
zipFile.close
The original example contained code to extract the file, but I merely want to read it directly into memory. Again, I don't know how exactly to work with this inputStream.
Could anyone give me a suggestion with a MWE?
It might be a little late, but maybe someone can use it:
(the code was tested in Matlab R2018a)
zipFilename = 'example.zip';
zipFile = org.apache.tools.zip.ZipFile(zipFilename);
entries = zipFile.getEntries;
while entries.hasMoreElements
entry = entries.nextElement;
entryName = char(entry.getName);
[~,~,ext] = fileparts(entryName);
if strcmp(ext,'.txt')
inputStream = zipFile.getInputStream(entry);
%Read the contents of the file
buffer = java.io.ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(inputStream, buffer);
data = char(typecast(buffer.toByteArray(), 'uint8')');
inputStream.close;
end
end
zipFile.close

Convert URL to normal windows filename Java 6

I am trying to read package name from a jar file. My probem is that when I get URL, it contains unrecognized form to be recognized by windows file.
I read this solution. But this did not helped me. Convert URL to normal windows filename Java.
directoryURL.toURI().getSchemeSpecificPart() does not convert windows style.
This is my code.
// Get a File object for the package
URL directoryURL = Thread.currentThread().getContextClassLoader()
.getResource(packageNameSlashed);
logger.info("URI" + directoryURL.toURI());
logger.info("Windows file Name" + directoryURL.toURI().getSchemeSpecificPart());
// build jar file name, then loop through zipped entries
jarFileName = URLDecoder.decode(directoryURL.getFile(), "UTF-8");
jarFileName = jarFileName.substring(0, jarFileName.indexOf(".jar"));
// HERE Throws exception"
jf = new JarFile(jarFileName + ".jar");
while (jarEntries.hasMoreElements()) {
entryName = jarEntries.nextElement().getName();
logger.info("Entry name: " + entryName);
if (entryName.startsWith(packageNameSlashed)
&& entryName.length() > packageNameSlashed.length() + 5
&& entryName.endsWith(".class")) {
entryName = entryName.substring(packageNameSlashed.length() + 1);
packageClassNames.put(entryName, packageName);
}
}
This is log.
16-02-2015 14:02:15 INFO - URI jar:file:/C:/SVN/AAA/trunk/aaa/client/target/server-1.0.jar!/packageName
16-02-2015 14:02:15 INFO Windows file Name file:/C:/SVN/AAA/trunk/aaa/client/target/server-1.0.jar!/packageName
A "jar:..." URL does not identify a file. Rather, it identifies a member of a JAR file.
The syntax is (roughly speaking) "jar:<jar-url>!<path-within-jar>", where the is itself a URL; e.g. a "file:" URL in your example.
If you are going to open the JAR file and iterate entries like that, you need to:
Extract the schemeSpecificPart of the original URL
Split the schemeSpecificPart on the "!" character.
Parse the part before the "!" as a URI, then use File(URI) to get the File.
Use the File to open the ZipFile.
Lookup the part after the "!" in the ZipFile ...
The answer by Stephen has all the elements you need.
With the getResource(package).getURI() or getResoucer(package).toFile you are getting the path to the resource.
Do substring on it to extract the part between file:// and ! this is the path to physical location of your jar of interest.
De new File on this sub-path and you have handle to your jar.
Jar is normal zip file, and process it as such (java.util.zip and there are manuals on the web).
List content of your zip file (now you may need to navigate using the bits behind ! sign in your original path), and you get your classes name.
I am not sure if this is the best way to achieve your goal, I would check how classes discovery (which is what you are trying to do, are implemented in some open source framework (for example tomcat uses it, JPA impelementation to find the entitities). There is also discovery project on apache but it seems to be dead for a while.

JAVA - zip4j, extract all text files ONLY from a zip file

we can extract all the files from a zoip filder using extractAll method given in zip4j, but what if i need to extract only one kind of files,say only text files or only files which have a certain sub-string in the name of the file?? is there a way to do this using zip4j
i thought this question might be relating to my problem
Read Content from Files which are inside Zip file
but that's not exactly what i want.
can anyone explain in detail about using this ZipEntry things, if it helps my problem getting solved?
Try the below code
ZipFile zipFile = new ZipFile("myzip.zip");
// Get the list of file headers from the zip file
List fileHeaderList = zipFile.getFileHeaders();
// Loop through the file headers
for (int i = 0; i < fileHeaderList.size(); i++) {
FileHeader fileHeader = (FileHeader)fileHeaderList.get(i);
String fileName = fileHeader.getFileName();
if(fileName.contains(".java")){
zipFile.extractFile(fileHeader, "c:\\scrap\\");
}
}

Get a file given a path to the file

I want to get a file which i saved in a specific directory on my phone.
How can I find and get a ref to it so I can do with it something different like uploading to a server?
Thanks in advance.
Shiran
Well where do you store your file?
Store the file in a specific area such as
Environment.getExternalStorageDirectory()
Then when you want to read it, just use the file name used and the path obtained from the above method.
File f = new File("location");
Remember, if you're trying to access the sd card you need to set permissions. Then just handle the "file" in whatever way it is you're trying to do something.
If you're looking to use the SDCard check this post:
Permission to write to the SD card
[Edit - Example]
String filenameToWrite = "Test.jpg"
try{
File f = new File(Environment.getExternalStorageDirectory() + "/Photos/");
if (f.exists()){
File fileToWrite = new File(Environment.getExternalStorageDirectory() + "/Photos/" + filenameToWrite;
// Do something to write file, save bitmap, save byte stream, etc.
}
} catch(IOException e){
Log.e("File", "Could not save file, error occured: " + e.toString());
}
Here's a few getting started tutorials to help you understand how to read and write files in java. This (apart from the 'path') is a java question, not an Android one.
Tutorials:
http://beginwithjava.blogspot.com/2011/04/java-file-save-and-file-load-objects.html
http://www.roseindia.net/java/beginners/java-write-to-file.shtml

Java: File output help

Fixed: Instead of calling isFile() I used exists() and it seems to be working fine. If possible could someone explain why this change worked?
I'm attempting to write out to an excel file but am having a problem when trying to create that file if the name already exists.
Basically I am taking a file that is uploaded to a server, reading it, and then outputting a report file in a new location with the same filename. I tried to do this by simply checking if the file already existed and then adding a number onto the filename. My code works if the file doesn't exist or if it exists without a number (e.g. filename.xls). If a file exists with the name "filename1.xls" the server just seems to hang when trying to write the file. What can do to fix this?
Here is my code:
String destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + ".xls";
int filenum = 1;
while (new File(destination).isFile()) {
destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + filenum + ".xls";
filenum++;
}
WritableWorkbook workbook = Workbook.createWorkbook(new File(destination));
That will happen if some process is still keeping the file open. E.g. you've created a FileInputStream on the file to read it, but are never calling close() on it after reading.
Unrelated to the problem, the expanded WAR folder is not the best place to use as a permanent storage. All those files in the expanded WAR folder will get lost whenever you redeploy the WAR. Also hardcoding a servletcontainer-specific path in the code makes it totally unportable.
If your actual intent is to return the Excel file on a per-request basis to the client using a servlet, then you should be using
WritableWorkbook workBook = Workbook.createWorkbook(response.getOutputStream());
// ...
This way it writes to the response immediately without the need for an intermediate file.
Use the File.createTempFile(prefix, suffix, directory) API:
String localName = new File(fileName).getName();
String nameNoExt = localName.substring(0, fileName.lastIndexOf("."));
String extension = localName.substring(fileName.lastIndexOf(".")); // need to include the .
File directory = new File("c:/apache-tomcat-7.0.8/webapps/reports/");
File destFile = File.createTempFile(nameNoExt, extension, directory)

Categories