java为word添加水印,图片水印和文字水印
jdk1.5及以上
所需jar包:Spire.Office.jar 或 Spire.Doc.jar
jar包下载:https://www.e-iceblue.cn/ 冰蓝科技,很不错的网站,值得研究研究。
或者要送我分也行,嘿嘿:Spire.Office.jar
下载步骤
下载前需要登录账号,若无账号则需注册。
下载时选择免费版,Free 开头的,否则生成的水印文件里会有jar包自带的水印。
Free Spire.Office for Java 是一套涵盖 E-iceblue 所有免费 Java 组件的集合,它包括以下产品的最新版本:Free Spire.Doc for Java, Free Spire.XLS for Java,Free Spire.Presentation for Java, Free Spire.PDF for Java 和 Free Spire.Barcode for Java。可以选其中的一种,也可下载整个Spire.Office。
jar包在压缩包的lib目录下。
官网自带的教程
这里找到这次需要的doc文件的教程,点它:
选择多行水印,文字水印或图片水印。若是水印图片的可以用我之前博客的生成水印图片的方法java为PDF添加水印,图片水印和文字水印
代码
import java.awt.Color;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.HeaderFooter;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ShapeLineStyle;
import com.spire.doc.documents.ShapeType;
import com.spire.doc.fields.ShapeObject;
public class WordUtil {
/**
* @param input 输入的文件路径
* @param output 输入的文件路径
* @param word 水印文字
* @throws Exception
*/
public static void addWordWaterMark(String input, String output, String word) throws Exception {
//加载示例文档
Document doc = new Document();
doc.loadFromFile(input);
//添加艺术字并设置大小
ShapeObject shape = new ShapeObject(doc, ShapeType.Text_Plain_Text);
shape.setWidth(120);
shape.setHeight(20);
//设置艺术字文本内容、位置及样式
//shape.setVerticalPosition(25);
//shape.setHorizontalPosition(25);
shape.setRotation(-25);//旋转角度
shape.getWordArt().setFontFamily("宋体");//字体
shape.getWordArt().setText(word);//文字
shape.setFillColor(Color.GRAY);//颜色
shape.setLineStyle(ShapeLineStyle.Single);
shape.setStrokeColor(new Color(192, 192, 192, 10));//new Color(red,green,blue,alpha-透明度)
shape.setStrokeWeight(1);
Section section;
HeaderFooter header;
for (int n = 0; n < doc.getSections().getCount(); n++) {
section = doc.getSections().get(n);
//获取section的页眉
header = section.getHeadersFooters().getHeader();
Paragraph paragraph;
if (header.getParagraphs().getCount() > 0) {
paragraph = header.getParagraphs().get(0);
} else {
paragraph = header.addParagraph();
}
for (int i = 0; i < 7; i++) {
//添加段落到页眉
paragraph = header.addParagraph();
for (int j = 0; j < 3; j++) {
//复制艺术字并设置多行多列位置
shape = (ShapeObject) shape.deepClone();
shape.setVerticalPosition(50 + 100 * i);//纵坐标
shape.setHorizontalPosition(10 + 160 * j);//横坐标
paragraph.getChildObjects().add(shape);
}
}
}
//保存文档
doc.saveToFile(output, FileFormat.Docx_2010);
}
public static void main(String[] args) throws Exception {
addWordWaterMark("E:\\测试.docx", "E:\\测试水印.docx", "管理员 2021-12-31");
}
}
doc,docx均可。只搞了文字水印的,图片水印看官网研究吧。嘿嘿