Java - POI - Add a picture to the header

南笙酒味 提交于 2019-12-10 00:26:36

问题


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?

Thanks in advance,

  • George

来源:https://stackoverflow.com/questions/30645062/java-poi-add-a-picture-to-the-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!