简体   繁体   中英

Apache poi replace existing picture on header

Is there any way to replace an image on word(docx) file header by name of the image with apache poi? I'am thinking about that:

+--------------------------------+
+HEADER myimage.jpeg-+
+ -----------BODY------------+
+--------------------------------+

replaceImage("myimage.jpeg", newPictureInputStream, "newPicture_name.jpeg");

Here what I tried:

    XWPFParagraph originalParagraph = null;
    originalParagraph = getPictureParagraphInHead(lookingPictureName);
    ListIterator<XWPFRun> it = originalParagraph.getRuns().listIterator();
    XWPFRun replacedRun = null;

    while (it.hasNext()) {
        XWPFRun run = it.next();
        int runIDX = it.nextIndex();
        if (run.getEmbeddedPictures().size() > 0) {
            XWPFRun newRun = null;
            newRun = new XWPFRun(run.getCTR(), (IRunBody) originalParagraph);
            originalParagraph.addRun(newRun);
            originalParagraph.removeRun(originalParagraph.getRuns().indexOf(run));
            break;
        }
    }

I'm not sure if you can get the "filename" of the image with POI. It's probably in the XML so you might have to make your own method for finding the image.

To get the Header you do:

XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(doc); // XWPFDocument
XWPFHeader header = policy.getDefaultHeader();

And to delete the images, get the XWPFRun from your paragraph (cell/row/table..)

CTR ctr = myRun.getCTR(); // 
List<CTDrawing> images = ctr.getDrawingList();
for (int i=0; i<images.size(); i++)
{
    ctr.removeDrawing(i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM