package com.jtyjy.pdf2pptx.converter;

import com.jtyjy.pdf2pptx.support.MyTask;
import com.lowagie.text.pdf.PdfReader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class Pdf2Png {

    private static final Logger logger = LoggerFactory.getLogger(Pdf2Png.class);

    private static int startPage = 0;

    private static int endPage = 0;

    // 执行标识
    private boolean exeFlag = true;

    public static void main(String[] args) {

//        pdf2Image("F:\\测试文档\\19届高三英语人教版第1期(1).pdf", "F:\\pdf图片", 350);
        int pages = 615;
        int totalPage = (pages + 7) / 8;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 1; i <= totalPage; i++) {
            map.put(i, i * 8);
        }
        System.out.println(totalPage);
    }

    /***
     * PDF文件转PNG图片，全部页数
     *
     * @param PdfFilePath pdf完整路径
     * @param PdfFilePath 图片存放的文件夹
     * @param dpi dpi越大转换后越清晰，相对转换速度越慢
     * @return
     */
    public static void pdf2Image(String PdfFilePath, String dstImgFolder, int dpi,ExecutorService executorService) {
        File file = new File(PdfFilePath);
        PDDocument pdDocument = null;
        try {
            String imgPDFPath = file.getParent();
            int dot = file.getName().lastIndexOf('.');
            // 获取图片文件名
            String imagePDFName = file.getName().substring(0, dot);
            String imgFolderPath = null;
            if (dstImgFolder.equals("")) {
                // 获取图片存放的文件夹路径
                imgFolderPath = imgPDFPath + File.separator + imagePDFName + "_图片";
            } else {
                imgFolderPath = dstImgFolder + File.separator + imagePDFName + "_图片";
            }
            if (createDirectory(imgFolderPath)) {

                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                /* dpi越大转换后越清晰，相对转换速度越慢 */
                PdfReader reader = new PdfReader(PdfFilePath);
                int pages = reader.getNumberOfPages();
                if (pages > 30) {
                    int totalPage = (pages + 5) / 6;
                    for (int i = 1; i <= 6; i++) {
                        startPage = endPage;
                        endPage = startPage + totalPage;
                        if (endPage > pages) {
                            endPage = pages;
                        }
                        executorService.execute(new MyTask(startPage, endPage, imgFolderPath, imagePDFName, file));
                        if (endPage == pages) {
                            break;
                        }
                    }
                    reader.close();
                } else {
                    endPage = pages;
                    ToImage(PdfFilePath, dpi, imagePDFName, imgFolderPath, renderer, endPage, startPage);
                    reader.close();
                    pdDocument.close();
                }
                startPage = 0;
                endPage = 0;
            } else {
                logger.info("PDF文档转PNG图片失败：" + "创建" + imgFolderPath + "失败");
            }

        } catch (IOException e) {
            logger.error("转换PDF文档：{} 错误：{}", PdfFilePath, e);
        }
    }

    private static void ToImage(String PdfFilePath, int dpi, String imagePDFName, String imgFolderPath, PDFRenderer renderer, int endPage, int startPage) throws IOException {
        StringBuffer imgFilePath;
        for (int i = startPage; i < endPage; i++) {
            String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;
            imgFilePath = new StringBuffer();
            imgFilePath.append(imgFilePathPrefix);
            imgFilePath.append("_");
            imgFilePath.append(String.valueOf(i + 1));
            imgFilePath.append(".png");
            File dstFile = new File(imgFilePath.toString());
            BufferedImage image = renderer.renderImageWithDPI(i, dpi);
            ImageIO.write(image, "png", dstFile);
        }
        logger.info("PDF文档：{} 转PNG图片成功！{}页-{}页", PdfFilePath, startPage + 1, endPage);
        System.err.println("PDF文档：[" + PdfFilePath + "] 转PNG图片成功！[" + startPage + 1 + "]页-[" + endPage + "]页");
    }

    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }

}
