import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.springframework.stereotype.Component;
import javax.swing.*;
import java.awt.*;
import java.io.FileOutputStream;
public class PDFAddWatermarkUtil {
/**
* 给PDF添加水印
*
* @param inputFile 原文件路径+名称
* @param outputFile 添加水印后输出文件保存的路径+名称
* @param waterMarkName 添加水印的内容
*/
public static void PDFAddWatermark(String inputFile, String outputFile, String waterMarkName) {
try {
String[] waterMarkContents = waterMarkName.split("\\|\\|");
// 间隔
int interval = 45;
// 获取水印文字的最大高度和宽度
int textH = 0, textW = 0;
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 获取总页数 +1, 下面从1开始遍历
int total = reader.getNumberOfPages() + 1;
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.2f);
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, 15);
// 设置颜色
// 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++) {
//ALIGN_LEFT
content.showTextAligned(Element.ALIGN_CENTER, waterMarkContents[z], width - textW, height - (textH + 10) * (z + 1), 30);
}
}
}
content.endText();
}
stamper.close();
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
java 实现pdf自定义水印
最新推荐文章于 2024-02-27 16:07:02 发布