水印使用的是itexpdf
1.引入依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2.相关代码
public static void addWatermark(String srcFile, String watermark) throws IOException, DocumentException {
// 待加水印的文件
PdfReader reader = new PdfReader(new FileInputStream(srcFile));
String outSrcPath = "D:\\waterMark.pdf";
// 加完水印的文件
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outSrcPath));
// 设置字体
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 设置透明度
PdfGState gs = new PdfGState();
// pdf页数
int pageCount = reader.getNumberOfPages() + 1;
PdfContentByte content;
// 循环对每页插入水印
for (int i = 1; i < pageCount; i++)
{
// 水印的起始
content = stamper.getOverContent(i);
gs.setFillOpacity(0.5f);
content.setGState(gs);
// 开始
content.beginText();
// 设置颜色 默认为黑色
content.setColorFill(BaseColor.LIGHT_GRAY);
// 设置字体及字号
content.setFontAndSize(baseFont, 50);
// 开始写入水印
content.showTextAligned(Element.ALIGN_BASELINE, watermark, 180,
340, 45);
content.endText();
}
stamper.close();
reader.close();
}
3.测试代码
public static void main(String[] args) throws IOException, DocumentException {
String srcFile = "D:\\174218509.pdf";
String warterMark = "这是水印水印水印";
addWatermark(srcFile,warterMark);
}