/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/9/17 9:26
 * Description:
 */
package com.emr.util;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Value;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class PDFUtils {

    public static void main(String[] args) throws IOException {
//        File[] pdfs = new File[9];
//        pdfs[0] = new File("C:\\Users\\Administrator\\Desktop\\病案pdf\\1422482_1\\d10db823-7af0-407f-bfb9-cb992a271dac.pdf");
//        pdfs[1] = new File("C:\\Users\\Administrator\\Desktop\\病案pdf\\1422482_1\\dc37ad48-5392-4239-bb07-d39a6d975a4b.pdf");
//        pdfs[2] = new File("C:\\Users\\Administrator\\Desktop\\病案pdf\\1422482_1\\4c981c6e-30a6-45de-a4d2-ec8ffa92b2ab.pdf");
//        pdfs[3] = new File("C:\\Users\\Administrator\\Desktop\\病案pdf\\1422482_1\\52dd7990-2377-4c3a-9b65-8bf0a72b0bfa.pdf");
//        pdfs[4] = new File("C:\\Users\\Administrator\\Desktop\\病案pdf\\1422482_1\\c145b11c-923d-4a4f-a387-2041ae08e4c0.pdf");
//
//        pdfs[5] = new File("C:\\Users\\Administrator\\Desktop\\病案pdf\\1422482_1\\c145b11c-923d-4a4f-a387-2041ae08e4c0.pdf");
//        pdfs[6] = new File("C:\\Users\\Administrator\\Desktop\\病案pdf\\1422482_1\\aaa58453-838f-49b0-8623-72188d7ef634.pdf");
//        pdfs[7] = new File("C:\\Users\\Administrator\\Desktop\\病案pdf\\1422482_1\\0000b5c4-5e91-4252-895c-b92560800064.pdf");
//        pdfs[8] = new File("C:\\Users\\Administrator\\Desktop\\病案pdf\\1422482_1\\1f9babf2-8e61-4659-aafa-7231fe6cbfd8.pdf");
//        File mergedPdf = new File("C:\\Users\\Administrator\\Desktop\\cs2\\MergedDiagram1.pdf");
//        try {
//            merge(pdfs, mergedPdf);
//        } catch (IOException | DocumentException e) {
//            e.printStackTrace();
//        }

        File f = new File("");
        String courseFile=f.getCanonicalPath();

        //System.out.println(courseFile+"sss");




        String projectPath = System.getProperty("user.dir");
        projectPath = projectPath.replace("bin", "webapps\\emr_medical_record\\static\\img\\pdfFiles\\typesPdf\\");
        //System.out.println("projectPath==" + projectPath);
        PDFUtils.delAllFile(projectPath);

        String path2= "C:\\Users\\Administrator\\Desktop\\测试\\aa\\";
        File outFile = new File(path2);
        //如果文件夹不存在则创建
        if (!outFile.exists() && !outFile.isDirectory()) {
            outFile.mkdirs();
        }
       // PDFUtils.delAllFile(path2);
        List pdfList = new ArrayList();
        pdfList.add("C:\\Users\\Administrator\\Desktop\\测试\\ttt.pdf");
        pdfList.add("C:\\Users\\Administrator\\Desktop\\测试\\sss.pdf");
        pdfList.add("C:\\Users\\Administrator\\Desktop\\测试\\15511.pdf");
        //List pdfError=getPdf("C:\\Users\\Administrator\\Desktop\\测试\\合成.pdf", pdfList);
        //System.out.println(pdfError.get(0));
    }

    //删除指定文件夹下的所有文件
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                //delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    public static List getPdf(String filePath, List pathArr){
        List pdfList = new ArrayList();
        if(pathArr!=null) {
            File[] pdfs = new File[pathArr.size()];
            for (int i = 0; i < pathArr.size(); i++) {
                pdfs[i] = new File(pathArr.get(i).toString());
            }
            File mergedPdf = new File(filePath);
            try {
                pdfList=merge(pdfs, mergedPdf);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return pdfList;
    }

    /**
     * @param pages
     * @param pdffile
     * @throws IOException
     * @throws DocumentException
     */
    public static List merge(File[] pages, File pdffile) throws IOException, DocumentException {
        List pdfList = new ArrayList();
        if (!pdffile.exists()) {
            pdffile.createNewFile();
        }
        //System.out.println(pages.length);
        if (pages.length >0) {
            Document document = new Document(new PdfReader(
                    ((File) pages[0]).getAbsolutePath()).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(pdffile));
            document.open();
            for (int i = 0; i < pages.length; i++) {
                //判断PDF是否损坏
                boolean bol = checkPdfFile(pages[i].toString());
                if (bol) {
                    PdfReader reader = new PdfReader((pages[i]).getAbsolutePath());
                    int num = reader.getNumberOfPages();
                    for (int j = 1; j <= num; j++) {
                        document.newPage();
                        PdfImportedPage page = copy.getImportedPage(reader, j);
                        copy.addPage(page);
                    }
                } else {
                    //列出所有损坏的文件信息
                    pdfList.add(pages[i].toString());
                }
            }
           // System.out.println("----------------------------------");

            copy.close();
            document.close();
//         for (File page : pages) {
//         page.deleteOnExit();
//         }
        }
        return pdfList;
    }


    private static boolean checkPdfFile(String file) {
        boolean flag1 = false;
        int n = 0;
        try {
            com.lowagie.text.pdf.PdfReader reader = new com.lowagie.text.pdf.PdfReader(file);
            com.lowagie.text.Document document = new com.lowagie.text.Document(reader.getPageSize(1));
            document.open();
            n = reader.getNumberOfPages();
            if (n != 0)
                flag1 = true;
            document.close();
        } catch (IOException e) {
            //System.out.println("文件{path:" + file + "}损坏" + e.fillInStackTrace());
            return false;
        }
        return flag1;


    }

    /**
     * 将base64字符串转换为PDF在显示到页面中
     * @param base64String
     * @param httpServletResponse
     */
    public static void base64StringToPDFToPage(String base64String, HttpServletResponse httpServletResponse){
        BASE64Decoder decoder = new BASE64Decoder();
        ByteArrayOutputStream baos = null;
        ServletOutputStream sos = null;
        try {
            byte[] bytes = decoder.decodeBuffer(base64String);
            baos = new ByteArrayOutputStream();
            baos.write(bytes); //把byte写进输出流里
            if (baos != null) {
                httpServletResponse.setContentType("application/pdf");
                httpServletResponse.setContentLength(baos.size());
                httpServletResponse.setHeader("Expires", "0");
                httpServletResponse.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                httpServletResponse.setHeader("Pragma", "public");
                // 设置打印PDF的文件名
                String fileName = "社保证明文件.pdf";
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                httpServletResponse.setHeader("Content-Disposition", "filename=" + fileName);
                sos = httpServletResponse.getOutputStream();
                baos.writeTo(sos); //byte输出流写入servlet输出流
                sos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                sos.close();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *  将base64编码转换成PDF
     *  @param base64String
     *  1.使用BASE64Decoder对编码的字符串解码成字节数组
     *  2.使用底层输入流ByteArrayInputStream对象从字节数组中获取数据；
     *  3.建立从底层输入流中读取数据的BufferedInputStream缓冲输出流对象；
     *  4.使用BufferedOutputStream和FileOutputSteam输出数据到指定的文件中
     */
    public static void base64StringToPDF(String base64String, String pdfPath/*File file*/){
        File file = new File(pdfPath);// 将原来参数修改为字符串
        BASE64Decoder decoder = new BASE64Decoder();
        BufferedInputStream bin = null;
        FileOutputStream fout = null;
        BufferedOutputStream bout = null;
        try {
            //将base64编码的字符串解码成字节数组
            byte[] bytes = decoder.decodeBuffer(base64String);
            //创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            //创建从底层输入流中读取数据的缓冲输入流对象
            bin = new BufferedInputStream(bais);
            //创建到指定文件的输出流
            fout  = new FileOutputStream(file);
            //为文件输出流对接缓冲输出流对象
            bout = new BufferedOutputStream(fout);

            byte[] buffers = new byte[1024];
            int len = bin.read(buffers);
            while(len != -1){
                bout.write(buffers, 0, len);
                len = bin.read(buffers);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节，必须这行代码，否则有可能有问题
            bout.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bout.close();
                fout.close();
                bin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * PDF转换为Base64编码
     * @param file
     * @return
     */
    public static String pdfToBase64(File file) {
        BASE64Encoder encoder = new BASE64Encoder();
        FileInputStream fin =null;
        BufferedInputStream bin =null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout =null;
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while(len != -1){
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            return encoder.encodeBuffer(bytes).trim();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fin.close();
                bin.close();
                baos.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * pdf转jpg
     * @param pdfPath
     * @param jpgPath
     */
    public static void pdfToJpg(String pdfPath,String jpgPath){
        long start = System.currentTimeMillis();
        //pdf路径
        InputStream stream = null;
        try {
            stream = new FileInputStream(new File(pdfPath));//URLUtil.getStream(url);
            // 加载解析PDF文件
            PDDocument doc = PDDocument.load(stream);
            PDFRenderer pdfRenderer = new PDFRenderer(doc);
            PDPageTree pages = doc.getPages();
            int pageCount = pages.getCount();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(bim, "jpg", os);
                byte[] datas = os.toByteArray();
                FileUtils.writeByteArrayToFile(new File(jpgPath),datas);
            }
            long end = System.currentTimeMillis();
            long time = (end - start) / 1000;
            System.out.println("pdf转jpg耗时： {}s"+time);
        }catch (Exception e){

        }

    }

    /**
     * base64转jpg
     * @param val
     * @param pdfFile
     * @param jpgFile
     */
    public static void base64ToJPG(String val,String pdfFile,String jpgFile){
        base64StringToPDF(val,pdfFile);
        pdfToJpg(pdfFile,jpgFile);
    }
}
 

