需要使用的依赖
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
工具类
源文件全路径和输出全路径最好不要写同一样的,不然有可能会报“java.io.FileNotFoundException:请求的操作无法在使用用户映射区域打开的文件上执行”的错误
package com.oims.util;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 给pdf文件加水印
*/
public class Util{
/**
* 给pdf文件加水印
* @param inputFile 源文件路径
* @param outputFile 输出文件路径
* @param waterMarkName 水印内容
* @return
*/
public static boolean waterMark(String inputFile,String outputFile, String waterMarkName) {
try {
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
//这里的字体设置比较关键,这个设置是支持中文的写法
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
int total = reader.getNumberOfPages() + 1;
PdfContentByte under;
Rectangle pageRect = null;
for (int i = 1; i < total; i++) {
pageRect = stamper.getReader().
getPageSizeWithRotation(i);
// 计算水印X,Y坐标
float x = 290;//pageRect.getWidth() / 2;
float y = 400;//pageRect.getHeight() / 2;
// 获得PDF最顶层
under = stamper.getOverContent(i);//在内容上方加水印
//under = stamper.getUnderContent(i);// 在内容下方加水印
under.saveState();
// set Transparency
PdfGState gs = new PdfGState();
// 设置透明度范围为0到1
gs.setFillOpacity(0.3f);
under.setGState(gs);
under.beginText();
under.setFontAndSize(base, 35);//字体大小
under.setColorFill(BaseColor.BLACK);//字体颜色
// 水印文字成45度角倾斜
under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, x, y, 45);
// 添加水印文字
under.endText();
under.setLineWidth(1f);
under.stroke();
}
stamper.close();
reader.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 方法调试
*/
public static void main(String[] args) throws Exception {
waterMark("D:\data\hello.pdf","D:\data\newHello.pdf","水印内容")
}
}