4

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
Nani
  • 45
  • 1
  • 4

2 Answers2

2

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

The code you have posted looks like you've just copy/pasted stuff without making any attempt to understand what you are doing. I say this because you're iterating through a bunch of XPath results, without doing anything with them.

wal
  • 17,409
  • 8
  • 74
  • 109
JasonPlutext
  • 15,352
  • 4
  • 44
  • 84
2

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).

Ben
  • 7,548
  • 31
  • 45