本文共 3837 字,大约阅读时间需要 12 分钟。
Apache POI库是处理Office文档格式的强大工具,主要用于读取、写入和转换各种文档文件。为确保本文档正常运行,需注意以下几点:
org.apache.poi poi 4.1.2 org.apache.poi poi-ooxml 4.1.2 org.apache.poi poi-ooxml-schemas 4.1.2
以下工具类DocxWaterMark用于在Word文档中添加水印,支持自定义内容、颜色和样式。代码结构清晰,易于扩展和维护。
package org.publiccms.common.watermark;import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.apache.poi.xwpf.usermodel.XWPFParagraph;import org.apache.xmlbeans.XmlObject;import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.regex.Pattern;public class DocxWaterMark { public static void addWaterMark(String filePath, String outPath, String waterMarkValue) throws Exception { InputStream in = new FileInputStream(new File(filePath)); XWPFDocument doc = new XWPFDocument(in); // 获取页眉页脚策略 XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy(); if (headerFooterPolicy == null) { headerFooterPolicy = doc.createHeaderFooterPolicy(); } // 设置水印内容 headerFooterPolicy.createWatermark(waterMarkValue); // 获取并修改水印样式 XWPFHeader header = headerFooterPolicy.getHeader(XWPFHeaderFooterPolicy.DEFAULT); XWPFParagraph paragraph = header.getParagraphArray(0); // 获取水印图形对象 XmlObject[] xmlobjects = paragraph.getCTP().getRArray(0).getPictArray(0).selectChildren( new javax.xml.namespace.QName("urn:schemas-microsoft-com:vml", "shape")); if (xmlobjects.length > 0) { CTShape ctshape = (CTShape) xmlobjects[0]; ctshape.setFillcolor("#f6f6f6"); ctshape.setStyle(ctshape.getStyle() + ";rotation:315"); ctshape.setStyle(getShapeStyle()); } // 输出文档 OutputStream out = new FileOutputStream(outPath); doc.write(out); out.flush(); out.close(); } // 修改水印样式高度的辅助方法 private static String getShapeStyle() { return "position: absolute; left: opt; width: 500pt; height: 150pt; z-index: -251654144; mso-wrap-edited: f; margin-left: -50pt; margin-top: 270pt; mso-position-horizontal-relative: margin; mso-position-vertical-relative: margin; mso-width-relative: page; mso-height-relative: page; rotation: 335"; } // 修改水印样式高度的方法 public static String getWaterMarkStyle(String styleStr, double height) { Pattern pattern = Pattern.compile(";"); String[] parts = styleStr.split(pattern); for (String part : parts) { if (part.startsWith("height:")) { styleStr = styleStr.replace(part, "height: " + height + "pt"); break; } } return styleStr; }} 以下代码示例展示了如何在实际应用中使用DocxWaterMark类添加水印:
DocxWaterMark dwm = new DocxWaterMark();String fileName = urlOfd.substring(urlOfd.lastIndexOf("/") + 1);String baseSrcUrl = this.preAbsoluteUrl + urlOfd.substring(urlOfd.lastIndexOf("upload") - 1, urlOfd.lastIndexOf("/")) + "/" + fileName;String baseOutUrl = this.preAbsoluteUrl + "\\waterMark" + urlOfd.substring(urlOfd.lastIndexOf("/"));try { dwm.addWaterMark(baseSrcUrl, baseOutUrl, username); msg = "success";} catch (Exception ex) { ex.printStackTrace();} 通过以上步骤,可以轻松集成POI库并为Word文档添加自定义水印,满足多种应用场景需求。
转载地址:http://jkxfk.baihongyu.com/