word文档动态插入水印,45度角,位于文档中央,可插入中文
word文档插入水印,网上有很多资料,但是很多是简单的参考例子,具体的细节,并没有考虑到
代码示意
代码片
.
/**
* @param inputFile 你的文件地址
* @param outputFile 添加水印后生成存放的地址
* @param waterMarkName 你的水印
* @return
*/
private static void insertWatermarkText(Document doc, String watermarkText) throws Exception {
Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
watermark.getTextPath().setText(watermarkText);
// 这里设置为宋体可以保证在转换为PDF时中文不是乱码.
watermark.getTextPath().setFontFamily("宋体");//Arial;
watermark.setWidth(200);
watermark.setHeight(50);
watermark.setRotation(-45);
Color color=new Color(Integer.parseInt("E0E0E0", 16));
watermark.getFill().setColor(color); //设置水印颜色
watermark.setStrokeColor(color); // 设置水印边框颜色
// 居中
// Place the watermark in the page center.
watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
watermark.setWrapType(WrapType.NONE); // TOP_BOTTOM : 将所设置位置的内容往上下顶出去
watermark.setVerticalAlignment(VerticalAlignment.CENTER);
watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
//将水印添加到Paragraph
Paragraph watermarkPara = new Paragraph(doc);
watermarkPara.appendChild(watermark);
//将水印Paragraph添加到每页的区域
for (Section sect : doc.getSections()) {
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);
}
// 参考下API : https://apireference.aspose.com/java/words/com.aspose.words/ShapeBase
doc.save("D:/image/12345.docx");
}
private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception {
HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);
if (header == null) {
header = new HeaderFooter(sect.getDocument(), headerType);
sect.getHeadersFooters().add(header);
}
header.appendChild(watermarkPara.deepClone(true));
}
private static void loadLicense() {
//返回读取指定资源的输入流
License license = new License();
InputStream is = null;
try {
is = WordTest.class.getClassLoader().getResourceAsStream("com/zy/water/license.xml");
if(is==null)
throw new RuntimeException("Cannot find licenses file. ");
license.setLicense(is);
} catch (Exception ex) {
ex.printStackTrace();
}finally{
if(is!=null){
try{ is.close(); }catch(IOException ex){ };
is = null;
}
}
}
jar包文件链接: jar包和licence文件