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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
import javax.swing.*;
import java.awt.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Objects;
/**
* @author zly
* @since 2020/8/13 16:46
*/
public class PdfAddWatermark {
private final static Logger logger = LoggerFactory.getLogger(PdfAddWatermark.class);
/**
* 字体路径
* private static final String TTF_PAHT = "TTF文件路径";
*/
private static final String TTF_PATH = Objects.requireNonNull(ClassUtils.getDefaultClassLoader().getResource("")).getPath() + "static/files/ttf";
/**
* 添加水印
* 备注:
* 在内容下方加水印
* content = stamper.getUnderContent(i);
* 间隔
* int interval = -5;
* 根据纸张大小多次添加, 水印文字成30度角倾斜
* for (int height = interval + textH; height < pageHeight; height = height + textH * 3) {
* for (int width = interval + textW; width < pageWidth + textW; width = width + textW * 2) {
* content.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 30);
* }
* }
*
* @param pdfPathAndName 原pdf位置
* @param waterMarkName 水印内容
* @param fileOutPutPathAndName 输出路径
*/
public static String pdfAddWatermark(String pdfPathAndName, String waterMarkName, String fileOutPutPathAndName) {
logger.info("-----------------------------pdf添加水印--------------------------------------");
long start = System.currentTimeMillis();
PdfReader reader = null;
PdfStamper stamper = null;
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(fileOutPutPathAndName)));
reader = new PdfReader(pdfPathAndName);
stamper = new PdfStamper(reader, bos);
// 获取总页数 +1, 下面从1开始遍历
int total = reader.getNumberOfPages() + 1;
// 使用classpath下面的字体库
BaseFont base = BaseFont.createFont(TTF_PATH + "/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 获取水印文字的高度和宽度
JLabel label = new JLabel();
label.setText(waterMarkName);
FontMetrics metrics = label.getFontMetrics(label.getFont());
// 文字高度
metrics.getHeight();
// 文字宽度
metrics.stringWidth(label.getText());
// 设置水印透明度
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.4f);
gs.setStrokeOpacity(0.4f);
Rectangle pageSizeWithRotation;
PdfContentByte content;
for (int i = 1; i < total; i++) {
// 在内容上方加水印
content = stamper.getOverContent(i);
content.saveState();
content.setGState(gs);
// 设置字体和字体大小
content.beginText();
content.setFontAndSize(base, 100);
// 获取每一页的高度、宽度
pageSizeWithRotation = reader.getPageSizeWithRotation(i);
float pageHeight = pageSizeWithRotation.getHeight();
float pageWidth = pageSizeWithRotation.getWidth();
content.showTextAligned(Element.ALIGN_LEFT, waterMarkName, pageWidth / 2 - 100, pageHeight / 2 - 100, 30);
content.endText();
}
long end = System.currentTimeMillis();
logger.info("------------------------pdf添加水印完成,用时:" + (end - start) + "ms--------------------------");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stamper != null) {
stamper.close();
logger.info("-------------------------------------流关闭-------------------------------------------");
}
} catch (Exception e) {
logger.error("----------------------pdf添加水印失败,异常信息:" + e.getMessage() + "--------------------------");
}
try {
if (reader != null) {
reader.close();
logger.info("-------------------------------------流关闭-------------------------------------------");
}
} catch (Exception e) {
logger.error("----------------------pdf添加水印失败,异常信息:" + e.getMessage() + "--------------------------");
}
}
return fileOutPutPathAndName;
}
}