首页 > 解决方案 > 如何使用 Apache POI 在现有 docx 文件中插入图像?

问题描述

问题是什么? 我在使用 Apache POI 将图像插入现有 docx 文件时遇到问题。当我打开 docx 文件时,我收到一条错误消息,指出该文件不可读。

什么时候出现问题? 当我使用“new XWPFDocument()”将图像插入到 XWPFDocument 的新实例中时,一切正常。当我使用现有 docx 文件的输入创建 XWPFDocument 的实例时,会弹出错误。

我想做什么? 当运行文本包含文本“[签名]”时,我想清除运行文本并在该运行中插入签名图像。

我使用的是哪个文件? 链接:https ://wetransfer.com/downloads/4cf6a680f290891a5fd53477d66c8abf20210616071837/41231b 。

我究竟做错了什么?

XWPFDocument doc = new XWPFDocument(new FileInputStream(inputURL));
doc = replaceFields(doc, replacings);

public static XWPFDocument replaceFields(XWPFDocument doc, HashMap<String, String> replacings) throws IOException, InvalidFormatException {
        int pCounter = 0;
        XWPFRun markedRun = null;
        for (XWPFParagraph p : doc.getParagraphs()) {
            pCounter++;
            List<XWPFRun> runs = p.getRuns();
            if (runs != null) {
                String text = "";
                int i = 1;
                for (XWPFRun run : runs) {
                    text = text + run.toString();
                    run.setText("", 0);
                    if (i == runs.size()) {
                        for (String key : replacings.keySet()) {
                            // Option 1: replacing value with trailing space
                            if (text.contains(key + " ") && replacings.get(key).equals("")) {
                                text = text.replace(key + " ", "");
                                continue;
                            }
                            // Option 2: Replacing value without trailing space
                            if (text.contains(key) && !replacings.get(key).equals("")) {
                                text = text.replace(key, replacings.get(key));
                                continue;
                            }
                            // Option 3: clearing empty values
                            if (text.contains(key) && replacings.get(key).equals("")) {
                                text = text.replace(key, "");
                                continue;
                            }
                        }
                        if (text.contains("[Signature]")) {
                            // Insert signature image
                            String signatureFile = "C:\\Users\\rick.van.baalen\\Downloads\\Prodin_Templates\\Signature_RVB.png";
                            InputStream is = new FileInputStream(signatureFile);
                            run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, signatureFile, Units.toEMU(80), Units.toEMU(65));
                            is.close();
                        } else {
                            run.setText(text);
                        }
                    }
                    i++;
                }
                System.out.println("Line " + pCounter + ": " + text);
            }
        }
        
        return doc;
    }

doc.write(new FileOutputStream(outputURL));

标签: javaapache-poidocx

解决方案


推荐阅读