Java代码实现对PDF的水印文字的添加。
水印的效果是:水印文字的换行、水印文字的平铺、水印文字的旋转。
import java.awt.FontMetrics;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JLabel;
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.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
public class TestWaterPrint {
public static void setWatermark(BufferedOutputStream bos, String input, String waterMarkContent)
throws DocumentException, IOException {
// 使用"||"将内容进行分割
String[] waterMarkContents = waterMarkContent.split("\\|\\|");
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, bos);
// 获取总页数 +1, 下面从1开始遍历
int total = reader.getNumberOfPages() + 1;
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 间隔
int interval = 20;
// 获取水印文字的最大高度和宽度
int textH = 0, textW = 0;
for (int j = 0; j < waterMarkContents.length; j++) {
JLabel label = new JLabel();
label.setText(waterMarkContents[j]);
FontMetrics metrics = label.getFontMetrics(label.getFont());
if (textH < metrics.getHeight()) {
textH = metrics.getHeight();
}
if (textW < metrics.stringWidth(label.getText())) {
textW = metrics.stringWidth(label.getText());
}
// 设置水印透明度
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.4f);
gs.setStrokeOpacity(0.4f);
Rectangle pageSizeWithRotation = null;
PdfContentByte content = null;
for (int i = 1; i < total; i++) {
content = stamper.getOverContent(i);
content.saveState();
content.setGState(gs);
// 设置字体和字体大小
content.beginText();
content.setFontAndSize(base, 20);
// 设置颜色
content.setColorFill(BaseColor.RED);
// 获取每一页的高度、宽度
pageSizeWithRotation = reader.getPageSizeWithRotation(i);
float pageHeight = pageSizeWithRotation.getHeight();
float pageWidth = pageSizeWithRotation.getWidth();
// 根据纸张大小多次添加, 水印文字成30度角倾斜
for (int height = interval + textH; height < pageHeight; height = height + textH * 6) {
for (int width = interval + textW; width < pageWidth + textW; width = width + textW * 2) {
// 将分段的字段进行输出编写
for (int z = 0; z < waterMarkContents.length; z++) {
content.showTextAligned(Element.ALIGN_LEFT, waterMarkContents[z], width - textW, height -(textH+10) * (z + 1), 30);
}
}
}
content.endText();
}
// 关闭流
stamper.close();
reader.close();
}
public static void main(String[] args) throws DocumentException, IOException {
// 输出的pdf文件
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("/Users/yangyun/Documents/personal_doc/pic/11.pdf")));
setWatermark(bos, "/Users/yangyun/Documents/personal_doc/pic/2020_PDF.pdf", "CSDN||stepMore||2020-5-30 11:19:12");
}
}