You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Apache POI向已创建的docx文档指定位置添加签名图片

问题描述

我在项目中使用Apache POI创建docx格式Word文档,文档生成后会通过邮件发送给审批人。我需要在审批人通过审核后,向已生成的Word文档的指定位置添加审批人的签名图片,但我不知道如何对已创建的文档执行该操作,想确认是否可以直接为已有文档添加图片,还是必须重新构建整个文档?

最初尝试的代码

我一开始写了如下代码段尝试实现需求:

FileInputStream docxFile=new FileInputStream(System.getProperty("jboss.server.data.dir")+"/corrolog/TestWS/"+strSO+" Test Workscope "+revision+".docx");
FileInputStream approverFile=new FileInputStream(approvers);
XWPFDocument doc = new XWPFDocument(docxFile);
List<XWPFParagraph> xwpfParagraphList = doc.getParagraphs();
for (XWPFParagraph xwpfParagraph : xwpfParagraphList) {
    for (XWPFRun xwpfRun : xwpfParagraph.getRuns()) {
        String text = xwpfRun.getText(0);
        System.out.println(text);
         if (text == "approved signature" && text.equals("approved signature")) {
             text.replace("approved signature", "");
             xwpfRun.setText(text);
             xwpfRun.addPicture(approverFile, XWPFDocument.PICTURE_TYPE_PNG, "approved", Units.toEMU(130), Units.toEMU(55));
         }
    }

}
FileOutputStream out = new FileOutputStream(System.getProperty("jboss.server.data.dir")+"/corrolog/TestWS/"+strSO+" Test Workscope "+revision+" Approved.docx");  
doc.write(out);
out.close();

但该代码无法成功向XWPFRun中添加图片。

可行解决方案

调整后的可正常运行代码如下:

String approvers=v2500Service.getApproverSignatures(approver).get(0).getImagePath();
FileInputStream approverFile=new FileInputStream(approvers);)
XWPFDocument doc = new XWPFDocument(Files.newInputStream(Paths.get(System.getProperty("jboss.server.data.dir")+"/corrolog/TestWS/EV13077-04 Test Workscope Rev0.docx")));
Iterator<IBodyElement> iter = doc.getBodyElementsIterator();
while (iter.hasNext()) {
   IBodyElement elem = iter.next();
   if (elem instanceof XWPFTable) {
       for(XWPFTableRow rows:((XWPFTable) elem).getRows())
       {
           for(XWPFTableCell cell:rows.getTableCells())
           {
               text=cell.getText();
               System.out.println(text);
               if(text.equals("approved signature"))
               {

                   text.replace("approved signature", "");
                   cell.getParagraphArray(0).removeRun(0);
                   cell.getParagraphArray(0).createRun();
                   cell.getParagraphArray(0).getRuns().get(0).addPicture(approverFile, XWPFDocument.PICTURE_TYPE_PNG, "approved", Units.toEMU(130), Units.toEMU(55));
               }
           }
       }
       System.out.println(((XWPFTable) elem).getRow(0).getCell(0).getText());
   } 
}

问题根因

我设置的占位符位于XWPFTable表格内,最初的代码仅遍历了文档的XWPFParagraph段落内容,无法命中表格内的占位符,需要额外遍历XWPFTable的所有单元格匹配占位符后再插入图片。


内容的提问来源于stack exchange,提问作者demir5334

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 21:00:02