使用Apache POI在Word文档中添加水印 [英] Add watermark in word document using Apache POI

查看:2744
本文介绍了使用Apache POI在Word文档中添加水印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add text watermark in word document using Apache POI.

我用过headerFooterPolicy.createWatermark("Watermark");,但是不显示对角灰色文本.

I have used headerFooterPolicy.createWatermark("Watermark"); but diagonal grayed text isn't displayed.

推荐答案

The private XWPFParagraph getWatermarkParagraph(String text, int idx) is simply not finished until now. You can waiting until it gets ready or manipulating it using the low level objects after the default was created.

所需的设置位于 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);
  }

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

 }
}

这篇关于使用Apache POI在Word文档中添加水印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆