Apache POI convert DOCX to PDF with EMF picture format. - java

I want to convert DOCX file that contains EMF pictures inside to PDF file. Apache POI detects EMF picture type, however it uses com.lowagie.text.Image class while converting to PDF. Unfortunately it doesn't support EMF format.
Do you have any idea how I can replace EMF pictures to JPG/GIF/BMP formats that are fully supported?
org.apache.poi.xwpf.converter.pdf version: 1.0.5
FileInputStream fis = new FileInputStream("file.docx");
XWPFDocument document = new XWPFDocument(OPCPackage.open(fis));
File outFile = new File("file.pdf");
OutputStream out = new FileOutputStream(outFile);
PdfOptions options = PdfOptions.create().fontEncoding("windows-1250");
PdfConverter.getInstance().convert(document, out, options);
The code above give an error:
Dec 21, 2015 10:26:56 AM
org.apache.poi.xwpf.converter.pdf.internal.PdfMapper visitPicture
SEVERE: The byte array is not a recognized imageformat.

Sadly, POI does not come with dedicated support for handling WMF/EMF. However, since the Windows GDI provides native support for rendering these formats, Word uses them as "preview images" (esp. for embedded OLEs) all the time.
For the case of WMF you may be able to succeed using Batik. See here. For EMF there is currently no (free) Java implementation AFAIK. All you could do is to
implement it yourself using this spec,
write something (platform-dependant) on top of the GDI or
(simple solution) feed the extracted EMFs back into Word (or any other member of the Office family such as PowerPoint/Visio) and batch process them into PNG using VBA.

Related

Using xdocreport, is it possible to read drawings from a docx file?

I need to convert a docx to a pdf. The following code use the library xdocreport and works pretty well.
The problem is for some specific docx which contain drawings. They are not visible in the final pdf. I've tested the conversion with the live demo avaible from the github and I've the same problem.
So I'm wondering, is this possible, or do I need to use an other library ? Which one ? (dox4j doesn't seems to works neither).
final XWPFDocument document = new XWPFDocument(inputStream);
final OutputStream outPdf = new FileOutputStream("myFile.pdf");
PdfConverter.getInstance().convert(document, outPdf, optionsPdf);
outPdf.close();
XDocReport doesn't support drawing. It could support it since docx->pdf is based on iText which supports draw, but it's a big task (any contribution are welcome!)
You can see here limitation of XDocReport docx->pdf converter.

how to modify metadata of a doc document

I'm looking to modify certain tags (like comments, keywords, etc) of a .DOC file. I've been able to do this for DOCX using docx4j but I haven't been able to find anything that lets me change the tags for a .DOC format.
Is there a way to programmatically change the content of certain tags in a .DOC file?
Apache POI will quite happily let you read and edit the metadata of supported documents. For the older OLE2 formats (.doc, .xls etc), you'll want to use HPSF, likely via POIDocument. For the OOXML formats (.docx, .xlsx etc) use POIXMLDocument and POIXMLProperties
To modify the OLE2 properties, you can either follow the detailed instructions and code in the HPSF documentation, or on newer version of POI you can short cut quite a bit of that with HPSFPropertiesOnlyDocument, eg
NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("test.doc"));
HPSFPropertiesOnlyDocument doc = new HPSFPropertiesOnlyDocument(fs);
SummaryInformation si = doc.getSummaryInformation();
if (si == null) doc.createInformationProperties();
si.setAuthor("StackOverflow");
si.setTitle("Properties Demo!");
FileOutputStream out = new FileOutputStream("changed.doc");
doc.write(out);
out.close();

convert a xls file as pdf without poi or jxl

So I summarize my problem. I would like to convert an xls file to PDF, while using java. .
I find two examples
The first is with Openoffice
import officetools.OfficeFile; // from officetools.jar
FileInputStream fis = new FileInputStream(new File("test.doc"));
FileOutputStream fos = new FileOutputStream(new File("test.pdf"));
OfficeFile f = new OfficeFile(fis,"localhost","8100", false);
f.convert(fos,"pdf");
But unfortunately I have to install it :(
I also find this example, two command line with vb (call pdf creator)
DoCmd.OpenReport "repClient", acViewPreview, "NumClient = 2"
DoCmd.OutputTo acOutputReport, "PDF", "d: \ test.pdf"
is there somthing like that on java !!!!
(Note I used for my first solution (jxl, appach poi) but formatting pdf generated is not like when I do save as PDF with Microsoft Excel)
think you in advance
I think you can stream the data from the excel document using
apache POI
library. You can pass this stream of data in
iText library API.
iText library API definitely has a function which writes stream data into PDF file. With iText, you can be sure of pdf formatting as it is widely used in organizations for PDF generation. Infact many reporting tool also use iText to generate PDF reports.

Creating PDF from Word (DOC) using Apache POI and iText in JAVA

I am trying to generate a PDF document from a *.doc document.
Till now and thanks to stackoverflow I have success generating it but with some problems.
My sample code below generates the pdf without formatations and images, just the text.
The document includes blank spaces and images which are not included in the PDF.
Here is the code:
in = new FileInputStream(sourceFile.getAbsolutePath());
out = new FileOutputStream(outputFile);
WordExtractor wd = new WordExtractor(in);
String text = wd.getText();
Document pdf= new Document(PageSize.A4);
PdfWriter.getInstance(pdf, out);
pdf.open();
pdf.add(new Paragraph(text));
docx4j includes code for creating a PDF from a docx using iText. It can also use POI to convert a doc to a docx.
There was a time when we supported both methods equally (as well as PDF via XHTML), but we decided to focus on XSL-FO.
If its an option, you'd be much better off using docx4j to convert a docx to PDF via XSL-FO and FOP.
Use it like so:
wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
// Set up font mapper
Mapper fontMapper = new IdentityPlusMapper();
wordMLPackage.setFontMapper(fontMapper);
// Example of mapping missing font Algerian to installed font Comic Sans MS
PhysicalFont font
= PhysicalFonts.getPhysicalFonts().get("Comic Sans MS");
fontMapper.getFontMappings().put("Algerian", font);
org.docx4j.convert.out.pdf.PdfConversion c
= new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);
// = new org.docx4j.convert.out.pdf.viaIText.Conversion(wordMLPackage);
OutputStream os = new java.io.FileOutputStream(inputfilepath + ".pdf");
c.output(os);
Update July 2016
As of docx4j 3.3.0, Plutext's commercial PDF renderer is docx4j's default option for docx to PDF conversion. You can try an online demo at converter-eval.plutext.com
If you want to use the existing docx to XSL-FO to PDF (or other target supported by Apache FOP) approach, then just add the docx4j-export-FO jar to your classpath.
Either way, to convert docx to PDF, you can use the Docx4J facade's toPDF method.
The old docx to PDF via iText code can be found at https://github.com/plutext/docx4j-export-FO/.../docx4j-extras/PdfViaIText/
WordExtractor just grabs the plain text, nothing else. That's why all you're seeing is the plain text.
What you'll need to do is get each paragraph individually, then grab each run, fetch the formatting, and generate the equivalent in PDF.
One option may be to find some code that turns XHTML into a PDF. Then, use Apache Tika to turn your word document into XHTML (it uses POI under the hood, and handles all the formatting stuff for you), and from the XHTML on to PDF.
Otherwise, if you're going to do it yourself, take a look at the code in Apache Tika for parsing word files. It's a really great example of how to get at the images, the formatting, the styles etc.
I have succesfully used Apache FOP to convert a 'WordML' document to PDF. WordML is the Office 2003 way of saving a Word document as xml. XSLT stylesheets can be found on the web to transform this xml to xml-fo which in turn can be rendered by FOP into PDF (among other outputs).
It's not so different from the solution plutext offered, except that it doesn't read a .doc document, whereas docx4j apparently does. If your requirements are flexible enough to have WordML style documents as input, this might be worth looking into.
Good luck with your project!
Wim
Use OpenOffice/LbreOffice and JODConnector
This also mostly works for .doc to .docx. Problems with graphics that I have not yet worked out though.
private static void transformDocXToPDFUsingJOD(File in, File out)
{
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
DocumentFormat pdf = converter.getFormatRegistry().getFormatByExtension("pdf");
converter.convert(in, out, pdf);
}
private static OfficeManager officeManager;
#BeforeClass
public static void setupStatic() throws IOException {
/*officeManager = new DefaultOfficeManagerConfiguration()
.setOfficeHome("C:/Program Files/LibreOffice 3.6")
.buildOfficeManager();
*/
officeManager = new ExternalOfficeManagerConfiguration().setConnectOnStart(true).setPortNumber(8100).buildOfficeManager();
officeManager.start();
}
#AfterClass
public static void shutdownStatic() throws IOException {
officeManager.stop();
}
You need to be running LibreOffice as a serverto make this work.
From the command line you can do this using;
"C:\Program Files\LibreOffice 3.6\program\soffice.exe" -accept="socket,host=0.0.0.0,port=8100;urp;LibreOffice.ServiceManager" -headless -nodefault -nofirststartwizard -nolockcheck -nologo -norestore
Another option I came across recently is using the OpenOffice (or LibreOffice) API (see here). I have not been able to get into this but it should be able to open documents in various formats and output them in a pdf format. If you look into this, let me know how it worked!

How to convert .doc or .docx files to .txt

I'm wondering how you can convert Word .doc/.docx files to text files through Java. I understand that there's an option where I can do this through Word itself but I would like to be able to do something like this:
java DocConvert somedocfile.doc converted.txt
Thanks.
If you're interested in a Java library that deals with Word document files, you might want to look at e.g. Apache POI. A quote from the website:
Why should I use Apache POI?
A major use of the Apache POI api is
for Text Extraction applications such
as web spiders, index builders, and
content management systems.
P.S.: If, on the other hand, you're simply looking for a conversion utility, Stack Overflow may not be the most appropriate place to ask for this.
Edit: If you don't want to use an existing library but do all the hard work yourself, you'll be glad to hear that Microsoft has published the required file format specifications. (The Microsoft Open Specification Promise lists the available specifications. Just google for any of them that you're interested in. In your case, you'd need e.g. the OLE2 Compound File Format, the Word 97 binary file format, and the Open XML formats.)
Use command line utility Apache Tika. Tika suports a wide number of formats (ex: doc, docx, pdf, html, rtf ...)
java -jar tika-app-1.3.jar -t somedocfile.doc > converted.txt
Programatically:
File inputFile = ...;
Tika tika = new Tika();
String extractedText = tika.parseToString(inputFile);
You can use Apache POI too. They have a tool to extract text from doc/docx Text Extraction. If you want to extract only the text, you can use the code below. If you want to extract Rich Text (such as formatting and styling), you can use Apache Tika.
Extract doc:
InputStream fis = new FileInputStream(...);
POITextExtractor extractor;
// if docx
if (fileName.toLowerCase().endsWith(".docx")) {
XWPFDocument doc = new XWPFDocument(fis);
extractor = new XWPFWordExtractor(doc);
} else {
// if doc
POIFSFileSystem fileSystem = new POIFSFileSystem(fis);
extractor = ExtractorFactory.createExtractor(fileSystem);
}
String extractedText = extractor.getText();
You should consider using this library. Its Apache POI
Excerpt from the website
In short, you can read and write MS
Excel files using Java. In addition,
you can read and write MS Word and MS
PowerPoint files using Java. Apache
POI is your Java Excel solution (for
Excel 97-2008). We have a complete API
for porting other OOXML and OLE2
formats and welcome others to
participate.
Docmosis can read a doc and spit out the text in it. Requires some infrastructure to be installed (such as OpenOffice).
You can also use JODConverter.

Categories

Resources