package cn.ezhizao.common.utils.pdf;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;

import javax.swing.*;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author wangshu
 */
public class PdfUtils {
    public static ByteArrayOutputStream addWaterMark(String inputFile, String text, String fontUrl) throws Exception {
        return addWaterMark(inputFile, text, fontUrl, 0.2f, 20, 45, 10, 1.4f);
    }

    /**
     * pdf添加水印
     *
     * @param inputFile     需要添加水印的文件
     * @param text          需要添加的水印文字
     * @param fontUrl       水印文本字体文件路径
     * @param opacity       水印字体透明度
     * @param fontSize      水印字体大小
     * @param angle         水印倾斜角度（0-360）
     * @param heightDensity 数值越大每页竖向水印越少
     * @param widthDensity  数值越大每页横向水印越少
     * @return
     * @throws Exception
     */
    public static ByteArrayOutputStream addWaterMark(String inputFile, String text, String fontUrl, float opacity,
                                                     int fontSize, int angle, float heightDensity, float widthDensity) throws Exception {
        // 0.读取原pdf
        PdfReader reader = new PdfReader(inputFile);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos);

        // 1.准备 字符串的高度、长度、透明度、字体类型 等参数
        JLabel label = new JLabel();
        FontMetrics metrics;
        int textH = 0;
        int textW = 0;
        label.setText(text);
        metrics = label.getFontMetrics(label.getFont());
        //字符串的高,   只和字体有关
        textH = metrics.getHeight();
        //字符串的宽
        textW = metrics.stringWidth(label.getText());
        // 水印透明度、字体设置
        PdfGState gs = new PdfGState();
        // 设置填充字体不透明度为0.2f
        gs.setFillOpacity(opacity);
        // 准备字体类型
        BaseFont base = BaseFont.createFont(fontUrl, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        // 2.循环PDF，每页添加水印
        PdfContentByte waterMar = null;
        Rectangle pageRect = null;
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            pageRect = reader.getPageSizeWithRotation(i);
            // 设置透明度、字体类型、字体大小
            waterMar = stamper.getOverContent(i);
            waterMar.saveState();
            waterMar.setGState(gs);
            waterMar.setFontAndSize(base, fontSize);
            // 开始添加水印
            waterMar.beginText();
            // 添加水印
            for (float height = textH; height < pageRect.getHeight() * 2; height = height + textH * heightDensity) {
                for (float width = textW; width < pageRect.getWidth() * 1.5 + textW; width = width + textW * widthDensity) {
                    waterMar.showTextAligned(Element.ALIGN_LEFT, text, width - textW, height - textH, angle);
                }
            }
            // 设置水印颜色
            waterMar.setColorFill(BaseColor.GRAY);
            //结束设置
            waterMar.endText();
            waterMar.stroke();
        }
        stamper.close();

        return bos;
    }

    public static ByteArrayOutputStream addText(String inputFile,String text,int fontSize,float x, float y,int rotation) throws IOException, DocumentException {
        // 读取原pdf
        PdfReader reader = new PdfReader(inputFile);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos);
        // 准备字体类型
        BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
        // 使用系统字体
        PdfContentByte waterMar = stamper.getOverContent(1);
        waterMar.beginText();
        waterMar.setFontAndSize(font, fontSize);
        waterMar.setColorFill(BaseColor.BLACK);
        waterMar.showTextAligned(Element.ALIGN_LEFT, text, x, y, rotation);
        waterMar.endText();
        stamper.close();
        return bos;
    }
    /**
     * 添加图片
     *
     * @param inputFile pdf文件地址
     * @param imagePath 图片地址
     * @param x         图片所在位置x
     * @param y         图片所在位置y
     * @param width     图片宽度
     * @param height    图片高度
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static ByteArrayOutputStream addImage(String inputFile, String imagePath, float x, float y, float width,
                                                 float height,int rotation,float opacity) throws IOException, DocumentException {
        // 读取原pdf
        PdfReader reader = new PdfReader(inputFile);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos);


        // 给每一页添加水印
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            PdfContentByte waterMark = stamper.getOverContent(i);
            addImage(waterMark, imagePath, x, y, width, height,rotation,opacity);
        }
        stamper.close();

        return bos;
    }

    private static void addImage(PdfContentByte waterMar, String imagePath, float x, float y, float width, float height,int rotation, float opacity)
            throws DocumentException, IOException {
        waterMar.beginText();
        // 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
        Image img = Image.getInstance(imagePath);
        img.setAbsolutePosition(x, y);
        img.scaleAbsolute(width, height);
        System.out.println(img.getImageRotation()+rotation);
        PdfGState gs = new PdfGState();
        // 设置填充字体不透明度为0.2f
        gs.setFillOpacity(opacity);
        img.setRotationDegrees(rotation);
        waterMar.setGState(gs);
        waterMar.addImage(img);
        // 设置水印颜色
        waterMar.setColorFill(BaseColor.GRAY);
        //结束设置
        waterMar.endText();
        waterMar.stroke();
    }

    /**
     * 移动 pdf
     * @param inputFile 源pdf文件路径
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static ByteArrayOutputStream movePdf(String inputFile,Integer cm,String direction) throws IOException, DocumentException {
        // 读取原pdf
        PdfReader reader = new PdfReader(inputFile);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos);
        // 给每一页添加水印
        int pageSize = reader.getNumberOfPages();
        for (int i = 1; i <= pageSize; i++) {
            switch (direction){
                case "left":
                    stamper.getUnderContent(i).setLiteral("\nq 1 0 0 1 "+cm+" 0 cm\nq\n");
                    break;
                case "right":
                    stamper.getUnderContent(i).setLiteral("\nq 1 0 0 1 -"+cm+" 0 cm\nq\n");
                    break;
                case "up":
                    stamper.getUnderContent(i).setLiteral("\nq 1 0 0 1 0 "+cm+" cm\nq\n");
                    break;
                case "down":
                    stamper.getUnderContent(i).setLiteral("\nq 1 0 0 1 0 -"+cm+" cm\nq\n");
                    break;
                default:
                    break;
            }
            stamper.getOverContent(i).setLiteral("\nQ\nQ\n");
        }
        stamper.close();
        System.out.println("White margin added to the right side of the PDF successfully!");
        return bos;


    }

    /**
     * 增加 pdf 宽/高
     * @param inputFile 源文件地址
     * @param cm 增加单位数
     * @param direction height/width
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    /**
     * 增加 pdf 宽/高
     * @param inputFile 源文件地址
     * @param cm 增加单位数
     * @param direction height/width
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static void reSized(String inputFile,String outputFile,Integer cm,String direction) throws IOException, DocumentException, COSVisitorException {
        // 读取原pdf
        PdfReader reader = new PdfReader(inputFile);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Rectangle pageSize =  reader.getPageSize(1);
        float newHeight = pageSize.getHeight();
        float newWidth = pageSize.getWidth();
        // 获取第一页的页面大小
        if("height".equals(direction)){
            // 增加高度，例如增加100个单位
            newHeight = pageSize.getHeight() + cm;
        }else if("width".equals(direction)){
            // 增加宽度，例如增加100个单位
            newWidth = pageSize.getWidth() + cm;
        }
        // 先生成空白的符合尺寸的pdf
        Rectangle newSize = new Rectangle(newWidth, newHeight);
        // 创建新的大小更大的页面
        PdfStamper stamper = new PdfStamper(reader, Files.newOutputStream(Paths.get(outputFile)), '\0', true);
        stamper.insertPage(2,newSize);
        stamper.getOverContent(2).addTemplate(stamper.getImportedPage(reader,1), 0, cm);
        // 删除第一页
        stamper.close();
        reader.close();
        PDDocument document = PDDocument.load(outputFile);
        document.removePage(0);
        document.save(outputFile);
        document.close();
        System.out.println("PDF resized successfully!");
    }
}
