package com.qmth.distributed.print;

import com.itextpdf.awt.AsianFontMapper;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class PDFWaterMarkTest {
    public static void main(String[] args) throws Exception {

        //需要添加水印的文件
        String inputFile = "D:\\基础和声1.pdf";
        //添加完水印的文件存放路径
        String outputFile = "D:\\基础和声1（水印）.pdf";
        //需要添加的水印文字
        String[] waterMarkName = {"添加水印", "dfsf"};
        //水印字体透明度
        float opacity = 0.5f;
        //水印字体大小
        int fontsize = 12;
        //水印倾斜角度（0-360）
        int rotation = 0;

        addWaterMark(inputFile, outputFile, waterMarkName, opacity, fontsize, rotation);
    }


    /**
     * pdf添加水印
     *
     * @param inputFile     需要添加水印的文件
     * @param outputFile    添加完水印的文件存放路径
     * @param waterMarkName 需要添加的水印文字
     * @param opacity       水印字体透明度
     * @param fontsize      水印字体大小
     * @param rotation         水印倾斜角度（0-360）
     */
    public static boolean addWaterMark(String inputFile, String outputFile, String[] waterMarkName,
                                       float opacity, int fontsize, int rotation) {
        File file = new File(inputFile);
        if (!file.exists()) {
            return false;
        }

        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            reader = new PdfReader(inputFile);
            stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            BaseFont base = BaseFont.createFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H, BaseFont.NOT_EMBEDDED);
            Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            //这里是透明度设置
            gs.setFillOpacity(opacity);
            //这里是条纹不透明度
            gs.setStrokeOpacity(0.2f);
            int total = reader.getNumberOfPages() + 1;
            System.out.println("Pdf页数：" + reader.getNumberOfPages());
            int textH = 0;
            int textW = 0;
            for (String s : waterMarkName) {
                JLabel label = new JLabel();
                FontMetrics metrics;

                label.setText(s);
                metrics = label.getFontMetrics(label.getFont());
                //字符串的高,   只和字体有关
                textH = metrics.getHeight();
                //字符串的宽
                textW = metrics.stringWidth(label.getText());
            }

            PdfContentByte under;
            //循环PDF，每页添加水印
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);  //在内容上方添加水印
                //under = stamper.getUnderContent(i);  //在内容下方添加水印
                under.saveState();
                under.setGState(gs);
                under.beginText();
                //under.setColorFill(BaseColor.PINK);  //添加文字颜色  不能动态改变 放弃使用
                under.setFontAndSize(base, fontsize); //这里是水印字体大小
                for (int j = 0; j < waterMarkName.length;j++) {
                    under.showTextAligned(Element.ALIGN_LEFT, waterMarkName[j], 10, pageRect.getHeight() - 30 - (j * textH), rotation);
                }
                //添加水印文字
                under.endText();
            }

            System.out.println("添加水印成功！");
            return true;
        } catch (IOException e) {
            System.out.println("添加水印失败！错误信息为: " + e);
            e.printStackTrace();
            return false;
        } catch (DocumentException e) {
            System.out.println("添加水印失败！错误信息为: " + e);
            e.printStackTrace();
            return false;
        } finally {
            //关闭流
            if (stamper != null) {
                try {
                    stamper.close();
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                reader.close();
            }
        }
    }
}
