java - 使用 Apache POI 在 Word 文档中添加水印

标签 java ms-word apache-poi

我想使用Apache POI在word文档中添加文本水印.

我使用了 headerFooterPolicy.createWatermark("Watermark"); 但不显示对角灰色文本。

最佳答案

private XWPFParagraph getWatermarkParagraph(String text, int idx)到现在为止根本就没有完成。您可以等待它准备好,或者在创建默认值后使用低级对象对其进行操作。

所需的设置位于 CTShape .

示例:

import java.io.*;

import org.apache.poi.xwpf.usermodel.*;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;

public class CreateWordHeaderFooterWatermark {

 public static void main(String[] args) throws Exception {

  XWPFDocument doc= new XWPFDocument();

  // the body content
  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run=paragraph.createRun();  
  run.setText("The Body:");

  // create header-footer
  XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy();
  if (headerFooterPolicy == null) headerFooterPolicy = doc.createHeaderFooterPolicy();

  // create default Watermark - fill color black and not rotated
  headerFooterPolicy.createWatermark("Watermark");

  // get the default header
  // Note: createWatermark also sets FIRST and EVEN headers 
  // but this code does not updating those other headers
  XWPFHeader header = headerFooterPolicy.getHeader(XWPFHeaderFooterPolicy.DEFAULT);
  paragraph = header.getParagraphArray(0);

  // get com.microsoft.schemas.vml.CTShape where fill color and rotation is set
  org.apache.xmlbeans.XmlObject[] xmlobjects = paragraph.getCTP().getRArray(0).getPictArray(0).selectChildren(
    new javax.xml.namespace.QName("urn:schemas-microsoft-com:vml", "shape"));

  if (xmlobjects.length > 0) {
   com.microsoft.schemas.vml.CTShape ctshape = (com.microsoft.schemas.vml.CTShape)xmlobjects[0];
   // set fill color
   ctshape.setFillcolor("#d8d8d8");
   // set rotation
   ctshape.setStyle(ctshape.getStyle() + ";rotation:315");
   //System.out.println(ctshape);
  }

  FileOutputStream out = new FileOutputStream("CreateWordHeaderFooterWatermark.docx");
  doc.write(out);
  out.close();
  doc.close();

 }
}

关于java - 使用 Apache POI 在 Word 文档中添加水印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48248276/

相关文章:

java.io.NotSerializedException : src. 项目 : How to get rid of having same repeated results to table?

java - Java上创建的HttpSession可以使用PHP的$_SESSION来访问吗

vba - 通过命令行或其他形式的自动化签署 Word VBA 项目/文件

java - 使用 =now() 公式时出现 Apache POI 日期区域设置错误

glassfish - Eclipse 中的 JRE 源文件

java - 枚举列表与 boolean 类

c# - 在线编辑 Word 文档的选项

c# - c#导出数据到word

java - 在java中修改大的excel(xlsx)文件

java apache poi - xwpfparagraph 到字符串转换