水印使用的是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.相關(guān)代碼
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));
// 設(shè)置字體
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 設(shè)置透明度
PdfGState gs = new PdfGState();
// pdf頁數(shù)
int pageCount = reader.getNumberOfPages() + 1;
PdfContentByte content;
// 循環(huán)對每頁插入水印
for (int i = 1; i < pageCount; i++)
{
// 水印的起始
content = stamper.getOverContent(i);
gs.setFillOpacity(0.5f);
content.setGState(gs);
// 開始
content.beginText();
// 設(shè)置顏色 默認(rèn)為黑色
content.setColorFill(BaseColor.LIGHT_GRAY);
// 設(shè)置字體及字號
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);
}