在开发中,下载 pdf 文件是一个非常普遍的功能,而在下载文件又需要保证自己的版权,这时候就需要给文件添加水印了,使用 Java 语言也可以给文件添加水印。
这里使用 maven 创建项目,添加依赖,如果不使用 maven ,可以下载对应的 jar 包即可。
jar包:itext-asian、itextpdf
前提:创建一个 maven 项目,添加依赖如下
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
写一个静态方法,添加设置,用于文件添加水印
/**
* @Description: TODO
* @author: scott
* @date: 2022/5/21 23:33
* @param bos: 文件输出位置
* @param input: 文件原位置
* @param waterMarkName: 水印内容
* @Return: void
*/
public static void setWatermark(BufferedOutputStream bos, String input, String waterMarkName)
throws DocumentException, IOException {
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, bos);
int total = reader.getNumberOfPages() + 1;
PdfContentByte content;
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 水印透明度
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.5f);
// 通过 for 循环,遍历每一页文档,并且添加水印
for (int i = 1; i < total; i++) {
content = stamper.getOverContent(i);
// 下方水印
content.beginText();
content.setColorFill(BaseColor.GRAY);
content.setFontAndSize(base, 16);
content.setTextMatrix(70, 200);
content.setGState(gs);
content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 200, 200, 30);
content.endText();
// 上方水印
content.beginText();
content.setColorFill(BaseColor.GRAY);
content.setFontAndSize(base, 16);
content.setTextMatrix(70, 200);
content.setGState(gs);
content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 200, 400, 30);
content.endText();
}
stamper.close();
}
注:
setGState 方法必须在 showTextAligned 方法之前,否则透明度将失效
.setColorFill(); // 设置水印颜色
.setFontAndSize(); // 设置水印字体
.setTextMatrix(); // 设置文本大小
.setGState(); // 设置水印透明度
.showTextAligned(); // 设置水印位置
调用:通过前面步骤,就可以直接调用生成下载文件并且添加水印了
public static void main(String[] args) throws DocumentException, IOException {
// 要输出的pdf文件
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:/new.pdf")));
// 将pdf文件先加水印然后输出
setWatermark(bos, "F:\ChromeFile\ces.pdf", "添加水印");
}
注:这里我本地 F:\ChromeFile 目录下有 ces.pdf 文件,内容为空,执行方法后,则会在D盘下创建 new.pdf 文件,并且添加水印。
结果:
源码地址:https://github.com/Yuqn/watermark.git
以上内容可能存在不足或错误,如有发现请指出来。