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 java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 转多页  完成
 * @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();    
        }    
    }   

}
