I have tried adding an image to the header of an XWPFDocument with no success. I am using Apache POI.
Here is what I am currently using as a solution:
Header creation
XWPFDocument document = new XWPFDocument(OPCPackage.open(docxInputStream));
CTP headerCtp = CTP.Factory.newInstance();
CTR headerCtr = headerCtp.addNewR();
XWPFParagraph headerParagraph = new XWPFParagraph(headerCtp, document);
XWPFRun run = headerParagraph.getRun(headerCtr);
InputStream pictureInputStream = new FileInputStream("D:\\logo.jpg");
run.addPicture(pictureInputStream, XWPFDocument.PICTURE_TYPE_JPEG, "logo.jpg", 300, 150);
pictureInputStream.close();
run.addTab();
run.setText(contentName);
setTabStop(headerCtp, STTabJc.Enum.forString("right"), BigInteger.valueOf(9000));
XWPFParagraph[] headerParagraphs = {headerParagraph};
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
headerFooterPolicy.createHeader(STHdrFtr.DEFAULT, headerParagraphs);
setTabStop method
private static void setTabStop(CTP oCTP, STTabJc.Enum oSTTabJc, BigInteger oPos) {
CTPPr oPPr = oCTP.getPPr();
if (oPPr == null) {
oPPr = oCTP.addNewPPr();
}
CTTabs oTabs = oPPr.getTabs();
if (oTabs == null) {
oTabs = oPPr.addNewTabs();
}
CTTabStop oTabStop = oTabs.addNewTab();
oTabStop.setVal(oSTTabJc);
oTabStop.setPos(oPos);
}
The trouble I am having is that the image is loaded in the run, meaning the size of the pictures array is 1, however it isn't getting displayed in the document.
I have tried numerous solutions such as the following ones:
Add image into a word .docx document header using Apache POI XWPF
how to add a picture to a .docx document with Apache POI XWPF in java
Java - POI - Add a picture to the header
How i can add an Image as my header in a word document using Apache POI
Any hints and ideas as to what I may be doing wrong are welcome.
Thanks.