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();