Search code examples
javams-worddocx4j

how to put images at a certain place in the Word(.docx) file by using DOCX4J in java


I have a requirement that I have a Word(.DOCX) file. by using a java program i need to put an image at a certain place in the document by using DOCX4J. can anyone please help me!!!

I'm trying with the following code...

 final String XPATH = "//w:t";
String image_Path = "D:\\Temp\\ex.png";
String template_Path = "D:\\Temp\\example.docx";

WordprocessingMLPackage  package =  WordprocessingMLPackage.createPackage();
List texts = package.getMainDocumentPart().getJAXBNodesViaXPath(XPATH, true);
for (Object obj : texts) {
  Text text = (Text) ((JAXBElement) obj).getValue();

  ObjectFactory factory = new ObjectFactory();         
  P paragraph = factory.createP();         
  R run = factory.createR();         
  paragraph.getContent().add(run);         
  Drawing drawing = factory.createDrawing();         
  run.getContent().add(drawing);         
  drawing.getAnchorOrInline().add(image_Path); 
  package.getMainDocumentPart().addObject(paragraph);
  package.save(new java.io.File("D:\\Temp\\example.docx"));here

Solution

  • You're just appending the image to the end of the document using that code. If you need it in a certain place within the document, you need to get a handle on where (for example, you might locate a specific P node using MainDocumentPart.getJAXBNodesViaXPath()), and then simply insert the new content at that 'index' within the document like so:

    package.getMainDocumentPart().getContent().add(index, imageParagraph);
    

    (You would derive the value for 'index' by using something like MainDocumentPart.getContent().indexOf(oldParagraph), and presumably would want to also remove the node you found, which is possible via a remove() call).