How to put images in a specific place in a Word file (.docx) using DOCX4J in java

I have a requirement that I have a Word file (.DOCX). using a java program, I need to put the image in a specific place in the document using DOCX4J. can anyone help me!

I am trying to use 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 
+4
source share
2 answers

You simply add an image to the end of the document with this code. If you need this in a specific place inside the document, you need to get a descriptor on where (for example, you can find the specific P node using MainDocumentPart.getJAXBNodesViaXPath() ), and then just insert the new content at this index 'inside the document:

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

(You will get the value for "index" using something like MainDocumentPart.getContent().indexOf(oldParagraph) , and presumably also want to remove the found node, which is possible by calling remove() ).

+2
source

There are more image additions than adding an empty Drawing object. See and understand the docx4j ImageAdd sample .

The code you posted looks like you just copied / pasted the material without trying to figure out what you are doing. I say this because you are repeating a bunch of XPath results without doing anything with them.

+2
source

Source: https://habr.com/ru/post/1485023/


All Articles