添加pdf水印

发布时间 2023-04-04 13:56:48作者: 橙香五花肉

添加pdf水印

依赖

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

代码

/**
 * 添加水印
 *
 * @param srcPdfPath        文件路径
 * @param tarPdfPath        添加水印后输出路径
 * @param waterMarkContent  水印文案
 * @param numberOfPage      每页需要插入的水印数
 */
public static void addPdfWaterMark(String srcPdfPath, String tarPdfPath, String waterMarkContent, int numberOfPage) {

    PdfReader reader = null;
    PdfStamper stamper = null;
    try {
        reader = new PdfReader(srcPdfPath);
        stamper = new PdfStamper(reader, Files.newOutputStream(Paths.get(tarPdfPath)));
        PdfGState gs = new PdfGState();

        //设置字体
        BaseFont font =  BaseFont.createFont("font/simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // 设置透明度
        gs.setFillOpacity(0.4f);

        int total = reader.getNumberOfPages() + 1;
        // 设置文本样式
        PdfContentByte content;

        for (int i = 1; i < total; i++) {
            content = stamper.getOverContent(i);
            content.beginText();
            content.setGState(gs);
            // 水印颜色
            content.setColorFill(BaseColor.DARK_GRAY);
            // 水印字体样式和大小
            content.setFontAndSize(font, 35);
            // 插入水印  循环每页插入的条数
            for (int j = 0; j < numberOfPage; j++) {
                /*
                    第一个参数:文字对齐方式
                    第二个参数:水印内容
                    第三个参数:x轴
                    第四个参数:y轴
                    第五个参数:水印旋转角度
                 */
                content.showTextAligned(Element.ALIGN_CENTER, waterMarkContent, 300, 500 * (j + 1), 30);
            }
            content.endText();
        }
    } catch (Exception e) {
        log.error("【添加水印失败】失败原因:{}", e.getMessage(), e);
        e.printStackTrace();
    } finally {
        try {
            if (null != stamper) {
                stamper.close();
            }
            if (null != reader) {
                reader.close();
            }
        } catch (DocumentException | IOException ignored) {}
    }
}

测试

public static void main(String[] args) {
    addWaterMark("你的文件路径", "C:/" + UUID.randomUUID() +".pdf", "超级无敌牛呗的水印", 1);
}