package com.gz;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class WatermarkPdf {


    public static void main(String[] args) throws IOException {
        File pdfFile = new File("F:\\错误\\5179-WS2020-001-0000-1145.pdf");
        //打开pdf文件
        PDDocument pdf = PDDocument.load(pdfFile);
        pdf.setAllSecurityToBeRemoved(true);
        for (PDPage page : pdf.getPages()) {
            PDPageContentStream cs = new PDPageContentStream(pdf, page, PDPageContentStream.AppendMode.APPEND, true, true);
            String ts = "刘长兰";
            //引入字体文件 解决中文汉字乱码问题
            PDFont font = PDType0Font.load(pdf, new FileInputStream("C:\\Windows\\Fonts\\STLITI.TTF"), true);
            float fontSize = 26;
            PDResources resources = page.getResources();
            PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
            // 水印透明度
            r0.setNonStrokingAlphaConstant(0.2f);
            r0.setAlphaSourceFlag(true);
            cs.setGraphicsStateParameters(r0);
            //水印颜色
            cs.setNonStrokingColor(153, 153, 153);
            cs.beginText();
            cs.setFont(font, fontSize);
            //根据水印文字大小长度计算横向坐标需要渲染几次水印
            float h = ts.length() * fontSize;
            for (int i = 0; i <= 5; i++) {
                // 获取旋转实例
                cs.setTextMatrix(Matrix.getRotateInstance(-150, i * 220, 0));
                cs.showText(ts);
                for (int j = 0; j < 10; j++) {
                    cs.setTextMatrix(Matrix.getRotateInstance(-150, i * 220, j * h * 2));
                    cs.showText(ts);
                }
            }
            cs.endText();
            cs.restoreGraphicsState();
            cs.close();
            pdf.save("F:\\Watermark.pdf");
        }

    }


}
