word填充、自动生成、添加水印

word内容填充生成,利用poi现用能力完成。通过对word中配置占位符(格式:{{字段名称}}),调用渲染API时传入对应字段名的值即可完成渲染。注意只支持扩展名为.docx的word操作,03版的不支持

引入依赖

<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.8.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>

配置格式word截图:

代码:

Map<String,Object> data = new HashMap();
//data中put对应字段的值,然后进行渲染
XWPFTemplate template =  XWPFTemplate.compile(inputStream).render(data);
FileOutputStream out = new FileOutputStream("//data//xxxxx.docx");
template.write(out);
out.flush();
template.close();

word中添加水印:题主用的也不多,简单贴一下代码。只支持单页word中添加一个水印,支持水印大小调整。

//输入的docx文档
InputStream in = new FileInputStream(new File("C:\\data\\CreateWordHeaderFooterWatermark.docx"));
XWPFDocument doc= new XWPFDocument(in);
XWPFParagraph paragraph = doc.createParagraph();

// 含有页眉时 使用这种方式不会报错
CTSectPr sectPr=doc.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy (doc,sectPr);
//水印名称,只支持文字水印
headerFooterPolicy.createWatermark("测试水印");
XWPFHeader header = headerFooterPolicy.getHeader(XWPFHeaderFooterPolicy.DEFAULT);
paragraph = header.getParagraphArray(0);
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];
    ctshape.setFillcolor("#d8d8d8");
    System.out.println(ctshape.getStyle());
    //上述的打印结果 position:absolute;margin-left:0;margin-top:0;width:415pt;height:207.5pt;z-index:-251654144;mso-wrap-edited:f
      ;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin 
    //可以改变style中的值,如果要修改高度则将height:207.5pt进行修改,其余的还有方向、z-index、位置、对齐方式等等
    ctshape.setStyle(ctshape.getStyle() + "rotation:315");
}else{
    System.out.print("加水印失败");
}
//加完水印后的文档地址及名称
doc.write(new FileOutputStream("C:\\data\\Watermark.docx"));
doc.close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值