package com.ktg.common.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

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

/**
 * PDF转换成长图片工具
 *
 * @author cgj
 */
public class PDFToImgUtil {

    public static String PDFToLongImgUtil(String pdfFilePath) {
        String outputFilePath = pdfFilePath.replace(".pdf", ".png"); // 输出文件路径
        try (PDDocument document = PDDocument.load(new File(pdfFilePath))) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);

            int totalHeight = 0;
            int maxWidth = 0;
            int dpi = 120; // 设置DPI

            // 获取每页图片的尺寸，并计算总高度和最大宽度
            BufferedImage[] images = new BufferedImage[document.getNumberOfPages()];
            for (int page = 0; page < document.getNumberOfPages(); ++page) {
                images[page] = pdfRenderer.renderImageWithDPI(page, dpi);
                totalHeight += images[page].getHeight();
                maxWidth = Math.max(maxWidth, images[page].getWidth());
            }

            // 创建一个新的BufferedImage来存储合并后的图片
            BufferedImage longImage = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = longImage.createGraphics();
            try {
                g2d.setColor(Color.WHITE); // 设置背景颜色为白色
                g2d.fillRect(0, 0, maxWidth, totalHeight);

                // 绘制每页图片到新的BufferedImage上
                int currentY = 0;
                for (BufferedImage image : images) {
                    g2d.drawImage(image, 0, currentY, null);
                    currentY += image.getHeight();
                    image.flush();
                }
            } finally {
                g2d.dispose(); // 确保Graphics2D对象被正确释放
            }

            // 保存合并后的图片
            ImageIO.write(longImage, "PNG", new File(outputFilePath));
            System.out.println("PDF转换为长图片成功！");
        } catch (IOException e) {
            System.err.println("发生错误: " + e.getMessage());
        }
        return outputFilePath;
    }

}
