package com.jtyjy.pdf2pptx.support;

import com.jtyjy.pdf2pptx.converter.Pdf2Png;
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;

public class MyTask implements Runnable {

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

    private  int startPage;

    private  int endPage;

    private String imgFolderPath;

    private String imagePDFName;

    private File file;

    @Override
    public void run() {
        PDDocument pdDocument = null;
        try {
            pdDocument = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            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, 150);
                logger.info("线程：{} 开始转换第{}页pdf", Thread.currentThread().getName(), i);
                ImageIO.write(image, "png", dstFile);
            }
        }catch (IOException e) {
            logger.error("转换图片出错：{}", e);
        }finally {
            if (pdDocument != null) {
                try {
                    pdDocument.close();
                } catch (IOException e) {
                    logger.error("错误：{}", e);
                }
            }
        }
        logger.info("PDF文档：{} 转PNG图片成功！{}页-{}页", file.getAbsolutePath(), startPage , endPage);

    }

    public int getStartPage() {
        return startPage;
    }

    public void setStartPage(int startPage) {
        this.startPage = startPage;
    }

    public int getEndPage() {
        return endPage;
    }

    public void setEndPage(int endPage) {
        this.endPage = endPage;
    }

    public MyTask(int startPage, int endPage,String imgFolderPath,String imagePDFName,File file) {
        this.startPage = startPage;
        this.endPage = endPage;
        this.imgFolderPath = imgFolderPath;
        this.imagePDFName = imagePDFName;
        this.file = file;
    }
    public MyTask() {
    }
}
