使用POI进行word标签替换及添加印章及签名图片方案
1.POI引用:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>ooxml-schemas</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.15</version> </dependency>
2.替换段落标签
功能代码如下:
File fileTem = new File(officeWordPath() + File.separator + tMobileWordSign.getWordPath()); InputStream iss = new FileInputStream(fileTem); XWPFDocument doc = new XWPFDocument(iss); DateFormat dateFormat = new SimpleDateFormat("yyyy 年 MM 月 dd 日"); List<XWPFParagraph> xwpfParagraphList = doc.getParagraphs(); //基本内容替换 for (XWPFParagraph xwpfParagraph : xwpfParagraphList) {
CTP ctp = xwpfParagraph.getCTP(); for (int dwI = 0; dwI < ctp.sizeOfBookmarkStartArray(); dwI++) { CTBookmark bookmark = ctp.getBookmarkStartArray(dwI); if (bookmark.getName().equals("year")) { XWPFRun run = xwpfParagraph.createRun(); run.setText(dateFormat.format(tMobileWordSign.getSignDate())); Node firstNode = bookmark.getDomNode(); Node nextNode = firstNode.getNextSibling(); while (nextNode != null) { // 循环查找结束符 String nodeName = nextNode.getNodeName(); if (nodeName.equals(BOOKMARK_END_TAG)) { break; } // 删除中间的非结束节点,即删除原书签内容 Node delNode = nextNode; nextNode = nextNode.getNextSibling(); ctp.getDomNode().removeChild(delNode); } if (nextNode == null) { // 始终找不到结束标识的,就在书签前面添加 ctp.getDomNode().insertBefore(run.getCTR().getDomNode(), firstNode); } else { // 找到结束符,将新内容添加到结束符之前,即内容写入bookmark中间 ctp.getDomNode().insertBefore(run.getCTR().getDomNode(), nextNode); } } } }
参考代码:https://blog.csdn.net/jmyyhw/article/details/100011782
3.添加印章及签名图片
在参考原有代码基础上,更进一步,同时一位置插入2个图片:一个印章图片,一个签字图片。考虑到印章图片一般为非透明,采用居于文字下方方式展示,签字一般为透明图片,采用浮于文字上方方式展现。
示例代码如下(非生产环境使用):
public void creatSealDocument()throws IOException,InvalidFormatException { XWPFParagraph currentParagraph = null; File fileTem = new File("d:\\关于在全市开展活动的通知.docx"); InputStream iss = new FileInputStream(fileTem); XWPFDocument doc = new XWPFDocument(iss); List<XWPFParagraph> xwpfParagraphList = doc.getParagraphs(); for (int i = 0; i < xwpfParagraphList.size(); i++) { XWPFParagraph x = xwpfParagraphList.get(i); List<CTBookmark> bookmarkList = x.getCTP().getBookmarkStartList(); for (int j = 0; j < bookmarkList.size(); j++) { System.out.println(bookmarkList.get(j).getName()); if (bookmarkList.get(j).getName().equals("sign")) { currentParagraph = x; break; } } } if (currentParagraph != null) { //添加印章图片 XWPFRun run = currentParagraph.createRun(); String imgFile1 = "d:\\t2.jpg"; FileInputStream is1 = new FileInputStream(imgFile1); run.addPicture(is1, XWPFDocument.PICTURE_TYPE_JPEG, imgFile1, Units.toEMU(60), Units.toEMU(60)); is1.close(); CTDrawing drawing1 = run.getCTR().getDrawingArray(0); CTGraphicalObject graphicalobject1 = drawing1.getInlineArray(0).getGraphic(); Random random = new Random(); int number = random.nextInt(999) + 1; //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 CTAnchor anchor1 = getAnchorWithGraphic(graphicalobject1, "Seal" + number, Units.toEMU(60), Units.toEMU(60),//图片大小 Units.toEMU(250), Units.toEMU(0), true);//相对当前段落位置及偏移 drawing1.setAnchorArray(new CTAnchor[]{anchor1});//添加浮动属性 drawing1.removeInline(0);//删除行内属性 //添加签名图片 run = currentParagraph.createRun(); imgFile1 = "d:\\t1.jpg"; FileInputStream is2 = new FileInputStream(imgFile1); run.addPicture(is2, XWPFDocument.PICTURE_TYPE_JPEG, imgFile1, Units.toEMU(60), Units.toEMU(60)); is2.close(); random = new Random(); CTDrawing drawing2 = run.getCTR().getDrawingArray(0); CTGraphicalObject graphicalobject2 = drawing2.getInlineArray(0).getGraphic(); number = random.nextInt(999) + 1; CTAnchor anchor2 = getAnchorWithGraphic(graphicalobject2, "Seal" + number, Units.toEMU(60), Units.toEMU(40),//图片大小 Units.toEMU(300), Units.toEMU(-5), false); drawing2.setAnchorArray(new CTAnchor[]{anchor2});//添加浮动属性 drawing2.removeInline(0);//删除行内属性 doc.write(new FileOutputStream("d:\\关于在全市开展活动的通知2.docx")); iss.close(); } doc.close(); }
getAnchorWithGraphic函数代码:
public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) { String anchorXML = "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" " + "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">" + "<wp:simplePos x=\"0\" y=\"0\"/>" + "<wp:positionH relativeFrom=\"column\">" + "<wp:posOffset>" + leftOffset + "</wp:posOffset>" + "</wp:positionH>" + "<wp:positionV relativeFrom=\"paragraph\">" + "<wp:posOffset>" + topOffset + "</wp:posOffset>" + "</wp:positionV>" + "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>" + "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>" + "<wp:wrapNone/>" + "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + deskFileName + "\"/><wp:cNvGraphicFramePr/>" + "</wp:anchor>"; CTDrawing drawing = null; try { drawing = CTDrawing.Factory.parse(anchorXML); } catch (XmlException e) { e.printStackTrace(); } CTAnchor anchor = drawing.getAnchorArray(0); anchor.setGraphic(ctGraphicalObject); return anchor; }
效果如下:
参考:
https://blog.csdn.net/a349687999/article/details/84983674
https://blog.csdn.net/kanglong129/article/details/103716052
4.输出word代码
String fileName = URLEncoder.encode("关于在全市开展活动的通知", "UTF8") + ".docx"; String reqBrowser = request.getHeader("User-Agent"); if (reqBrowser.toLowerCase().indexOf("firefox") > 0) { fileName = new String("关于在全市开展活动的通知".getBytes("UTF-8"), "ISO8859-1") + ".docx"; } String headStr = "attachment; filename=\"" + fileName + "\""; response.reset(); response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); response.setHeader("Content-Disposition", headStr); OutputStream out = response.getOutputStream(); out.flush(); doc.write(out); out.flush(); doc.close(); out.close();