1.添加依赖
<!-- pdf打水印 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
2.下载所需要的字体
去找到相关字体的ttf文件,这里使用的是宋体。 可以使用如下连接下载。 「simsun.ttf」www.aliyundrive.com/s/STggfheok… 提取码: 9uw3 点击链接保存,或者复制本段内容,打开「阿里云盘」APP ,无需下载极速在线查看,视频原画倍速播放。
3.添加工具类
package com.hobby.item.util;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.springframework.util.StreamUtils;
import java.io.*;
/**
* PDF 加水印
*/
public class PdfMarkUtil {
public static byte[] addWatermark(InputStream inputStream, String watermark) throws IOException, DocumentException {
PdfReader reader = new PdfReader(inputStream);
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
PdfStamper stamper = new PdfStamper(reader, os);
int total = reader.getNumberOfPages() + 1;
PdfContentByte content;
// 设置字体
String fontPath = "C:\Users\Administrator\Downloads\simsun.ttf";
//设置字体
BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 循环对每页插入水印
for (int i = 1; i < total; i++) {
// 水印的起始
content = stamper.getUnderContent(i);
// 开始
content.beginText();
// 设置颜色
content.setColorFill(new BaseColor(244, 244, 244));
// 设置字体及字号
content.setFontAndSize(baseFont, 50);
// 设置起始位置
content.setTextMatrix(400, 780);
for (int x = 0; x < 5; x++) {
for (int y = 0; y < 5; y++) {
content.showTextAlignedKerned(Element.ALIGN_CENTER,
watermark,
(100f + x * 350),
(40.0f + y * 150),
30);
}
}
content.endText();
}
stamper.close();
return os.toByteArray();
} finally {
reader.close();
}
}
public static void main(String[] args) throws IOException, DocumentException {
File file = new File("C:\Users\Administrator\Desktop\test.pdf");
InputStream inputStream = new FileInputStream(file);
byte[] bytes = addWatermark(inputStream, "哈哈哈水印");
OutputStream outputStream = new FileOutputStream(new File("C:\Users\Administrator\Desktop\test-mark.pdf"));
StreamUtils.copy(bytes,outputStream);
outputStream.close();
}
}