简体   繁体   中英

Insert .pdf doc or .png image content into a .docx file using java

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"); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM