package com.yeejoin.amos.boot.module.jg.biz.utils;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;

import javax.imageio.ImageIO;
import java.awt.Font;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Administrator
 */

public class PdfUtils {

    @SneakyThrows
    public static File addImageToPdf(String inputPdfPath, int width, int height, String imagePath) {
        PdfReader reader = null;
        PdfStamper stamper = null;
        File outputPdfFile = null;
        try {
            reader = new PdfReader(inputPdfPath);
            outputPdfFile = File.createTempFile("output", ".pdf");
            stamper = new PdfStamper(reader, new FileOutputStream(outputPdfFile));
            Image img = Image.getInstance(imagePath);
            img.scaleToFit(width, height);
            PdfContentByte content = stamper.getOverContent(1);
            img.setAbsolutePosition(reader.getPageSize(1).getWidth() - width, reader.getPageSize(1).getHeight() - height);
            content.addImage(img);
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (stamper != null) {
                try {
                    stamper.close();
                } catch (DocumentException | IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                reader.close();
            }
        }
        return outputPdfFile;
    }


    public static void generatorImageWithText(File imageFile, int width, int height, String text, Color color) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();
        // 设置背景为透明
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d.dispose();
        g2d = image.createGraphics();

        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 写入字符串
        Font font = new Font("Microsoft YaHei", Font.BOLD, 20);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int textWidth = fm.stringWidth(text);
        int textHeight = fm.getHeight();

        int x = (width - textWidth) / 2;
        int y = (height - textHeight) / 2 + fm.getAscent();

        g2d.setColor(color);
        g2d.drawString(text, x, y);
        g2d.dispose();
        try {
            ImageIO.write(image, "PNG", imageFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @SneakyThrows
    public static File addFullPageWatermark(String src, String watermarkText) {
        PdfReader reader = null;
        PdfStamper stamper = null;
        File outputPdfFile = null;
        try {
            outputPdfFile = File.createTempFile("output", ".pdf");
            reader = new PdfReader(src);
            stamper = new PdfStamper(reader, new FileOutputStream(outputPdfFile));
            PdfGState gs = new PdfGState();
            // 设置透明度为0.1
            gs.setFillOpacity(0.5f);
            int n = reader.getNumberOfPages();
            // 创建一个BaseFont实例，用于水印文本
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            // 设置水印文本大小
            float fontSize = 40;
            // 设置水印文本的间距、根据字体大小调整行间距
            float lineSpacing = fontSize + 2;
            // 设置水印文本的起始位置
            float x = 0;
            // 遍历PDF的每一页
            for (int i = 1; i <= n; i++) {
                PdfContentByte over = stamper.getOverContent(i);
                // 获取页面尺寸
                Rectangle pageSize = reader.getPageSizeWithRotation(i);
                float pageWidth = pageSize.getWidth();
                float pageHeight = pageSize.getHeight();

                // 从页面底部开始
                float y = pageHeight;
                // 计算文本宽度
                float textWidth = bf.getWidthPoint(watermarkText, fontSize);
                // 添加水印文本到页面
                while (y > 0) {
                    // 文本从页面左侧开始
                    x = 60;
                    while (x < pageWidth) {
                        over.beginText();
                        over.setFontAndSize(bf, fontSize);
                        //水印颜色
                        over.setColorFill(BaseColor.LIGHT_GRAY);
                        over.setGState(gs);
                        // 设置文本渲染模式为填充，使文本不可选择
                        over.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
                        over.setTextMatrix(x, y);
                        over.showTextAligned(Element.ALIGN_CENTER, watermarkText, x, y, 45);
                        over.endText();
                        // 更新x坐标以跳过当前行的文本宽度
                        x += textWidth + lineSpacing;
                    }
                    // 当一行文本添加完毕后，减少y坐标以开始新的一行
                    y -= (lineSpacing + 50);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stamper != null) {
                stamper.close();
            }
            if (reader != null) {
                reader.close();
            }
        }
        return outputPdfFile;
    }


}
