JAVA给PDF添加水印
Java给PDF文件添加水印
因为在项目中需要用到这个功能所以自己写了一下,现在分享一下
加入maven依赖
代码片
.
// An highlighted block
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
</dependency>
代码实现
/**
*
* @param InPdfFile 文件地址
* @param outPdfFile 输出文件地址
* @param textWatermark 水印文字
* @return
* @throws IOException
* @throws DocumentException
*/
public static boolean addPngWatermark(String InPdfFile, String outPdfFile, String textWatermark)
throws IOException, DocumentException {
try {
PdfReader reader = new PdfReader(InPdfFile);
// reader.unethicalreading = true;
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outPdfFile));
// 这里的字体设置比较关键,这个设置是支持中文的写法
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);// 使用系统字体
int total = reader.getNumberOfPages();
// 文字的长度
int l = textWatermark.length();
int size = 0;
if (l <= 6) {
size = 22;
}
if (l > 6 && l <= 11) {
size = 15;
}
if (l > 11) {
size = 10;
}
if (l > 15) {
size = 5;
}
Font f = new Font(base, size);
Phrase p = new Phrase(textWatermark, f);
// transparency
PdfGState gs1 = new PdfGState();
// 设置水印透明度
gs1.setFillOpacity(0.4f);
PdfContentByte over;
com.itextpdf.text.Rectangle pagesize;
for (int i = 1; i <= total; i++) {
pagesize = reader.getPageSizeWithRotation(i);
over = stamper.getOverContent(i);
over.saveState();
over.setGState(gs1);
over.setTextMatrix(30, 30);
over.setColorFill(BaseColor.GRAY);
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 8; x++) {
// 水印文字成45度角倾斜
ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 80 + 140 * x, 158 * y, -45);
}
}
over.restoreState();
}
stamper.close();
reader.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
测试效果
public static void main(String[] args) {
try {
PdfWatermark.addPngWatermark("D:\\home\\file\\vert-x-core-manual-for-java.pdf", "D:\\home\\file\\vert-x-core-manual-for-java_ceshi.pdf", "测试水印");
} catch (Exception e) {
e.printStackTrace();
}
}
结束语
这个就是Java给PDF添加水印的实现,期间也在网上找了些资料。有什么问题欢迎大家来交流