I have a template DOCX file that I am working with. The template file contains two placeholders for images (a logo and a barcode image). How can I replace these images using BufferedImage or just getting an image from a URL? There seem to not be many resources on this.
Asked
Active
Viewed 95 times
1 Answers
0
I finally got it to work using bookmarks. Apparently I didn't dig deeper before posting the question. The code is below. Although I did not find the methods to control the width and height of the image, which is important, the code below does answer my question.
public void addLogoAndBarCode(WordprocessingMLPackage pack, String agencyID)
{
MainDocumentPart documentPart = pack.getMainDocumentPart();
Document wmlDoc = (Document) documentPart.getJaxbElement();
Body body = wmlDoc.getBody();
List<Object> paragraphs = body.getContent();
RangeFinder rt = new RangeFinder("CTBookmark", "CTMarkupRange");
new TraversalUtil(paragraphs, rt);
for(CTBookmark bm:rt.getStarts())
{
if(bm.getName().equals("agencyLogo"))
{
logger.info("i found bookmark");
try
{
InputStream is = new FileInputStream(agencyLogoPath+agencyID+".jpg");
byte[] bytes = IOUtils.toByteArray(is);
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(pack, bytes);
Inline inline = imagePart.createImageInline(null, null, 0,1, false, 800);
P p = (P)(bm.getParent());
ObjectFactory factory = new ObjectFactory();
R run = factory.createR();
Drawing drawing = factory.createDrawing();
drawing.getAnchorOrInline().add(inline);
run.getContent().add(drawing);
p.getContent().add(run);
}
catch(Exception er)
{
er.printStackTrace();
}
}
}
}

javalove
- 560
- 3
- 9
-
1If you have a reference to the image part, you can replace the image contents in the part. Doing this retains the existing properties (height, width) specified in the existing anchor. I expect the createImageInline approach in the answer above will leave your placeholder images present in the docx zip file, even though they are not visible? – JasonPlutext Nov 21 '22 at 22:03