1.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.surpass</groupId>
<artifactId>pdf</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>pdf</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.2</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
</project>
2.PDF文件添加水印
public void waterMark(String inputFile, String outputFile, String waterMarkName) {
PdfReader reader = null;
PdfStamper stamper = null;
try {
reader = new PdfReader(inputFile);
stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
// 使用系统字体
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 设置水印参数
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.3f);
gs.setStrokeOpacity(1.0f);
// 计算PDF总页数
int total = reader.getNumberOfPages() + 1;
// 循环对每一页加水印
Rectangle pageRect;
PdfContentByte under;
// 初始化高度间隔
int interValHeigh = 0;
// 初始化纵坐标
int yPosition = -100;
for (int i = 1; i < total; i++) {
pageRect = reader.getPageSizeWithRotation(i);
// 获取page高度
int pageHeight = Float.valueOf(pageRect.getHeight()).intValue();
//重新计算高度间隔
interValHeigh = pageHeight / 3;
// 得到一个覆盖在上层的水印文字
under = stamper.getOverContent(i);
under.saveState();
under.setGState(gs);
under.beginText();
// 设置水印文字颜色
under.setColorFill(BaseColor.BLACK);
// 设置水印文字和大小
under.setFontAndSize(base, 20);
yPosition = yPosition + pageHeight + interValHeigh;
do {
yPosition = yPosition - interValHeigh;
under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, 200, yPosition, 30);
} while (yPosition > 0 );
under.endText();
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
// 关闭流
try {
if (stamper != null) {
stamper.close();
}
if (reader != null) {
reader.close();
}
} catch (Exception e) {
}
}
}