Reputation: 9
How can I insert pdf or png content into a docx file using java?
I've tried using Apache POI API in the following way, but it is not working (it generates some junk doc file):
XWPFDocument doc = new XWPFDocument();
String pdf = "D://capture1.pdf";
PdfReader reader = new PdfReader(pdf);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
TextExtractionStrategy strategy = parser.processContent(i,new SimpleTextExtractionStrategy());
String text = strategy.getResultantText();
XWPFParagraph p = doc.createParagraph();
XWPFRun run = p.createRun();
run.setText(text);
run.addBreak(BreakType.PAGE);
}
FileOutputStream out1 = new FileOutputStream("D://javadomain1.docx");
doc.write(out1);
out1.close();
reader.close();
System.out.println("Document converted successfully");
Upvotes: 0
Views: 3298
Reputation: 15863
You should be able to do it with POI, and you can certainly do it using docx4j.
Here's sample code for inserting an image using docx4j.
Note that to "insert a PDF", you need to OLE embed it. That's more difficult, since you need to convert the PDF to a suitable binary OLE object. In docx4j, helper code for doing this is part of the commercial Enterprise edition.
Upvotes: 3