用Apache POI替换图像

时间:2016-09-24 20:09:47

标签: java apache-poi

我需要帮助,方法是使用Apache POI或任何其他可能完成工作的库,将图像替换为Word中的其他图像。我知道如何使用Apache POI替换单词,但我无法找到替换图像的方法。

public static void main(String[] args) throws FileNotFoundException {

    String c22 = "OTHER WORD";

    try {
        XWPFDocument doc = new XWPFDocument(OPCPackage.open("imagine.docx"));
        for (XWPFParagraph p : doc.getParagraphs()) {
            List<XWPFRun> runs = p.getRuns();
            if (runs != null) {
                for (XWPFRun r : runs) {
                    String text = r.getText(0);
                    if (text != null ) {
                        String imgFile = "imaginedeschis.jpg";
                         try (FileInputStream is = new FileInputStream(imgFile)) {
                             r.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imgFile,
                                          Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
                             text = text.replace("1ST WORD", c22);
                         } // 200x200 pixels
                         r.setText(text, 0);
                    }
                }
            }  
        }       
        doc.write(new FileOutputStream("output.docx"));
    } catch (InvalidFormatException | IOException m){ }
}

1 个答案:

答案 0 :(得分:2)

我在Java代码下使用替换Word文档中的一个图像(* .docx)。如果有人有更好的方法,请分享。

    public XWPFDocument replaceImage(XWPFDocument document, String imageOldName, String imagePathNew, int newImageWidth, int newImageHeight) throws Exception {
    try {
        LOG.info("replaceImage: old=" + imageOldName + ", new=" + imagePathNew);

        int imageParagraphPos = -1;
        XWPFParagraph imageParagraph = null;

        List<IBodyElement> documentElements = document.getBodyElements();
        for(IBodyElement documentElement : documentElements){
            imageParagraphPos ++;
            if(documentElement instanceof XWPFParagraph){
                imageParagraph = (XWPFParagraph) documentElement;
                if(imageParagraph != null && imageParagraph.getCTP() != null && imageParagraph.getCTP().toString().trim().indexOf(imageOldName) != -1) {
                    break;
                }
            }
        }

        if (imageParagraph == null) {
            throw new Exception("Unable to replace image data due to the exception:\n"
                    + "'" + imageOldName + "' not found in in document.");
        }
        ParagraphAlignment oldImageAlignment = imageParagraph.getAlignment();

        // remove old image
        document.removeBodyElement(imageParagraphPos);

        // now add new image

        // BELOW LINE WILL CREATE AN IMAGE
        // PARAGRAPH AT THE END OF THE DOCUMENT.
        // REMOVE THIS IMAGE PARAGRAPH AFTER 
        // SETTING THE NEW IMAGE AT THE OLD IMAGE POSITION
        XWPFParagraph newImageParagraph = document.createParagraph();    
        XWPFRun newImageRun = newImageParagraph.createRun();
        //newImageRun.setText(newImageText);
        newImageParagraph.setAlignment(oldImageAlignment);
        try (FileInputStream is = new FileInputStream(imagePathNew)) {
            newImageRun.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imagePathNew,
                         Units.toEMU(newImageWidth), Units.toEMU(newImageHeight)); 
        } 

        // set new image at the old image position
        document.setParagraph(newImageParagraph, imageParagraphPos);

        // NOW REMOVE REDUNDANT IMAGE FORM THE END OF DOCUMENT
        document.removeBodyElement(document.getBodyElements().size() - 1);

        return document;
    } catch (Exception e) {
        throw new Exception("Unable to replace image '" + imageOldName + "' due to the exception:\n" + e);
    } finally {
        // cleanup code
    }
}

请访问https://bitbucket.org/wishcoder/java-poi-word-document/wiki/Home了解更多示例,例如:

  • 打开现有的Microsoft Word文档(* .docx)
  • Word文档中的克隆表并将新数据添加到克隆表
  • 更新文档中的现有表格&gt;单元格数据
  • 更新文档中的现有超链接
  • 替换文档中的现有图像
  • 保存更新Microsoft Word文档(* .docx)