0

I have been trying to add a picture to a new docx file using Java POI to the header.

  1. I have added a header, and added a text to it (using XWPFHeaderFooterPolicy).

  2. I have create an image (using CustomXWPFDocument).

  3. But I could not insert the image inside the header area. I have tried to do so through adding the picture into the same paragraph of the header, but it did not work.

Here is the function that should add the picture to the header. It takes a CustomXWPFDocument object that has been already created:

    private void addLogo(CustomXWPFDocument doc) throws InvalidFormatException, IOException, XmlException
{
    
    String imgFile = "1.jpg";

    CTP ctp = CTP.Factory.newInstance();
    CTR ctr = ctp.addNewR();
    CTText textt = ctr.addNewT();
    textt.setStringValue( " Page 1" );
    XWPFParagraph codePara = new XWPFParagraph( ctp, doc );
    XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
    
    //add logo
    String blipId = codePara.getDocument().addPictureData(new FileInputStream(new File(imgFile)), Document.PICTURE_TYPE_PNG);
    doc.createPicture(blipId, doc.getNextPicNameNumber(Document.PICTURE_TYPE_PNG), 200, 200);       
    
    //
    newparagraphs[0] = codePara;
    CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
    XWPFHeaderFooterPolicy headerFooterPolicy = new  XWPFHeaderFooterPolicy( doc, sectPr );
    headerFooterPolicy.createFooter( STHdrFtr.DEFAULT, newparagraphs );
    headerFooterPolicy.createHeader( STHdrFtr.DEFAULT, newparagraphs );
    
}

Here is the link for the custom class: how to add a picture to a .docx document with Apache POI XWPF in java

I have looked around and saw others asking about it, but without a solution. Any ideas?

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
George7a
  • 63
  • 8

0 Answers0