简体   繁体   English

用 Apache POI 替换图像

[英]Replace a image with Apache POI

I need help by replacing an image with another image in Word using Apache POI or any other library that might do the job.我需要帮助,通过使用 Apache POI 或任何其他可能完成这项工作的库在 Word 中将图像替换为另一个图像。 I know how to replace a word using Apache POI but I can't figure a way out to replace an image.我知道如何使用 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){ }
}

I am using below Java code to replace one image in Word document (*.docx).我正在使用下面的 Java 代码替换 Word 文档 (*.docx) 中的一张图片。 Please share if anyone have better approach.如果有人有更好的方法,请分享。

    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
    }
}

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

  • Open existing Microsoft Word Document (*.docx)打开现有的 Microsoft Word 文档 (*.docx)
  • Clone Table in Word Document and add new data to cloned table在 Word 文档中克隆表并将新数据添加到克隆表中
  • Update existing Table->Cell data in document更新文档中现有的表格->单元格数据
  • Update existing Hyper Link in document更新文档中的现有超链接
  • Replace existing Image in document替换文档中的现有图像
  • Save update Microsoft Word Document (*.docx)保存更新 Microsoft Word 文档 (*.docx)

I recommend using transparent tables to track images.我建议使用透明表格来跟踪图像。 following code will replace table row 0 col 1 cell's picture.以下代码将替换表格行 0 col 1 单元格的图片。

List<XWPFParagraph> paragraphs = table.getRow(0).getCell(1).getParagraphs(); 
    
            for (XWPFParagraph para: paragraphs) {
                for (XWPFRun r : para.getRuns()) {
                    CTR ctr = r.getCTR();
                    List<CTDrawing> drawings = ctr.getDrawingList();
                    for (int i = 0; i < drawings.size(); i++) {
                        ctr.removeDrawing(i);
                    }
                }
            }
            
    
            XWPFParagraph paragraph = table.getRow(0).getCell(1).addParagraph(); 
            XWPFRun run = paragraph.createRun();
            
         
 
            FileInputStream fis = new FileInputStream('filepath');
            run.addPicture(fis, XWPFDocument.PICTURE_TYPE_PNG, "filename", Units.toEMU(200), Units.toEMU(60)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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