package com.yizhi.application.certificate.util;

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 javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 转多页  完成
 * @author wangfeida
 *
 */
public class PdfToPng {

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

	/***
     * PDF文件转PNG图片
     * @param pdfPath        E:\png\简历.pdf
     * @param outputFilePath 图片存放的文件夹    E:\png
     * @param dpi dpi越大转换后越清晰，相对转换速度越慢
     * @param flag 页数 为0则转换全部页数
     * @return
	 * @throws IOException
     */
    public static  String pdfToPng(String pdfPath, String outputFilePath, int dpi,int flag,String filename) throws IOException {
        File file = new File(pdfPath);
        PDDocument pdDocument = null;
        try {
           if (createDirectory(outputFilePath)) {
                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                int pages = pdDocument.getNumberOfPages();
                if(flag > 0) {//大于0则打印具体页数
                    if(flag<pages) {
                        pages = flag;
                    }
                }
                StringBuffer imgFilePath = null;
                for (int i = 0; i < pages; i++) {
                    String imgFilePathPrefix = outputFilePath+File.separator;
                    imgFilePath = new StringBuffer();
                    imgFilePath.append(imgFilePathPrefix);
                    imgFilePath.append(filename);
                    imgFilePath.append(".png");
                    File dstFile = new File(imgFilePath.toString());
                    BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                    ImageIO.write(image, "png", dstFile);
                }
                System.out.println(outputFilePath+"1111");
                return outputFilePath;

            } else {
                return "创建文件夹错误";
            }
        } catch (Exception e) {
            logger.info("Pdf转Png发生错误", e.getMessage());
            return "Pdf转Png转换发生错误";
        }finally {
            pdDocument.close();
        }

    }

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


    public static void pdfFileToImage(File pdffile,String targetPath){
        try {
            FileInputStream instream = new FileInputStream(pdffile);
            InputStream byteInputStream=null;
            try {
                PDDocument doc = PDDocument.load(instream);
                PDFRenderer renderer = new PDFRenderer(doc);
                int pageCount = doc.getNumberOfPages();
                if (pageCount > 0) {
                    BufferedImage image = renderer.renderImage(0, 2.0f);
                    image.flush();
                    ByteArrayOutputStream bs = new ByteArrayOutputStream();
                    ImageOutputStream imOut;
                    imOut = ImageIO.createImageOutputStream(bs);
                    ImageIO.write(image, "png", imOut);
                    byteInputStream = new ByteArrayInputStream(bs.toByteArray());
                    byteInputStream.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            File uploadFile = new File(targetPath);
            FileOutputStream fops;
            fops = new FileOutputStream(uploadFile);
            fops.write(readInputStream(byteInputStream));
            fops.flush();
            fops.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

//    public static void main(String[] args) {
//        File file =new File("D:\\test\\qwe123.pdf");
//        //上传的是png格式的图片结尾
//        String targetfile="D:\\test\\qwe123.png";
//        try {
////            pdfFileToImage(file,targetfile);
//
//            pdfToPng("D:\\test\\qwe123.pdf","D:\\test\\",500,0,"qwe1234");
//        } catch (Exception e) {
//        }
//
//
//
//    }

}
