1.增加pom依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2.java工具方法
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfStamper stamp = null;
PdfReader reader = null;
try {
//获取创建读取Pdf文件流对象
reader = new PdfReader("pdf文件路径");
stamp = new PdfStamper(reader, outputStream);
//pdf文件页数
int keywords = reader.getNumberOfPages();
// 插入水印
Image img = Image.getInstance("印章文件路径");
// 水印透明度设置
PdfGState gs1 = new PdfGState();
gs1.setFillOpacity(0.8f);
//遍历文件页数,可用于多页签字
for (int i = 1; i <= keywords; i++) {
//签字第几页 getUnderContent:在内容下方,getOverContent:在内容上方
PdfContentByte pdfContentByte = stamp.getOverContent(keywords);
//设置图片长和宽
img.scaleAbsolute(200, 100);
//插入水印位置坐标
img.setAbsolutePosition(300, 100);
//img.setRotation(-20);// 旋转 弧度
//img.setRotationDegrees(45);// 旋转 角度
// img.scalePercent(50);//依照比例缩放
// 图片水印 透明度
pdfContentByte.setGState(gs1);
//插入图片水印
pdfContentByte.addImage(img);
}
//关闭流
stamp.close();
//生成新文件
File tempFile = new File("合成新文件路径");
if (!tempFile.exists()) {
tempFile.createNewFile();
}
//写入新文件内容
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
fileOutputStream.write(outputStream.toByteArray());
fileOutputStream.close();
//base64字节流数据
//String output = Base64.encodeBase64String(outputStream.toByteArray());
System.out.println("签字盖章成功");
}catch (Exception e){
System.out.println("签字盖章异常:"+e);
} finally {
if (null != reader) {
reader.close();
}
}
3.项目运行,OK