/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/7/31 19:49
 * Description:
 */
package com.emr.util;

import com.emr.entity.Archive_Detail;
import com.emr.entity.Emr_Picture;
import com.emr.entity.MergePDFItem;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.*;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * 将多张图片合并转为PDF；需要用到iTextpdf包，
 *
 * @author
 */
public class PrintToPdfUtil {
    final private static float A4_weight = 595;//标准A4的宽
    final private static float A4_height = 842;//标准A4的高
    /**
     * 经过测试,dpi为96,100,105,120,150,200中,
     * 120,150,200显示效果较为清晰,体积稳定,dpi越高图片体积越大
     */
    public static final float DEFAULT_DPI = 200;
    public static final String DEFAULT_FORMAT = "jpg";

    public static boolean forceDelete(File file) {
        boolean result = file.delete();
        int tryCount = 0;
        while (!result && tryCount++ < 10) {
            System.gc();    //回收资源
            result = file.delete();

        }
        return result;
    }

    /***
     * @param picturePath
     *            图片地址
     */
    private static void createPic( String picturePath,Document document) {
        try {
            File file=new File(picturePath);
            File[] files = file.listFiles();
            Image img =null;

            if (files.length > 0) {
                for (File file1 : files) {
                    if (file1.getName().endsWith(".png") || file1.getName().endsWith(".jpg") || file1.getName().endsWith(".gif")
                            || file1.getName().endsWith(".jpeg") || file1.getName().endsWith(".tif")) {
                        // 实例化图片
                        img = Image.getInstance(file1.getPath());
                        /*处理图片缩放比例*/
                        float w = img.getWidth();
                        float h = img.getHeight();
                        float percent = 0;
                        if ((w > A4_weight) && (h < A4_height)) {
                            percent = (A4_weight * 100) / w;
                        } else if ((w < A4_weight) && (h > A4_height)) {
                            percent = (A4_height * 100) / h;
                        } else if ((w > A4_weight) && (h > A4_height)) {
                            percent = (A4_weight * 100) / w;
                            h = (h * percent) / 100;
                            if (h > A4_height) {
                                percent = (A4_height * 100) / h;
                            }
                        }

                        // 读取图片流
                        img.setAlignment(com.lowagie.text.Image.ALIGN_CENTER);
                        if(percent != 100){
                            img.scaleAbsolute(A4_weight,A4_height);
                        }else{
                            img.scalePercent(percent);
                        }
                        document.open();
                        document.add(img);

                    }else if(file1.isDirectory()){
                        //是文件夹迭代
                        System.out.println(file1.getAbsolutePath());
                        createPic(file1.getAbsolutePath(),document);
                    }
                }
            }
            document.close();
        } catch (Exception ex) {
        }
    }

    public static void image2pdf(String text,List dirList) throws DocumentException, IOException {
       /* Document document = new Document();
        OutputStream os = new FileOutputStream(new File(pdf));
        PdfWriter.getInstance(document, os);
        document.open();*/
        //循环类别
        if(dirList.size()>0){
            for(int i=0;i<dirList.size();i++){
                Document document = new Document();
                OutputStream os = new FileOutputStream(new File(text+dirList.get(i)+"//"+dirList.get(i)+".pdf"));
                PdfWriter.getInstance(document, os);
                // document.open();
                File file=new File(text+dirList.get(i));
                File[] files = file.listFiles();
                if (files.length > 0) {
                    // 循环获取图片文件夹内的图片，全部
                    createPic(text+dirList.get(i),document);

                }

            }
        }
    }

    public static String imgsListTopdf(String pdfPath,List<Emr_Picture> imgsList) throws DocumentException, IOException {
        String result="合成pdf成功";
        File file=new File(pdfPath);
        if(file.exists()){
            file.delete();
        }
        //循环类别
        if(pdfPath.length()>0){
            file=new File(pdfPath);
            Document document = new Document();
            OutputStream os = new FileOutputStream(file);
            PdfWriter.getInstance(document, os);
            document.open();
            if(imgsList.size()>0){
                Image img =null;
                File file1=null;
                String info="";
                for(int j=0;j<imgsList.size();j++){
                    file1=new File(imgsList.get(j).getMaxPicture());
                    if(file1!=null && file1.isFile()) {
                        if (file1.getName().endsWith(".png") || file1.getName().endsWith(".jpg") || file1.getName().endsWith(".gif")
                                || file1.getName().endsWith(".jpeg") || file1.getName().endsWith(".tif")) {
                            // 实例化图片
                            img = Image.getInstance(file1.getPath());
                            /*处理图片缩放比例*/
                            float w = img.getWidth();
                            float h = img.getHeight();
                            float percent = 0;
                            if ((w > A4_weight) && (h < A4_height)) {
                                percent = (A4_weight * 100) / w;
                            } else if ((w < A4_weight) && (h > A4_height)) {
                                percent = (A4_height * 100) / h;
                            } else if ((w > A4_weight) && (h > A4_height)) {
                                percent = (A4_weight * 100) / w;
                                h = (h * percent) / 100;
                                if (h > A4_height) {
                                    percent = (A4_height * 100) / h;
                                }
                            }

                            // 读取图片流
                            img.setAlignment(com.lowagie.text.Image.ALIGN_CENTER);
                            if (percent != 100) {
                                img.scaleAbsolute(A4_weight, A4_height);
                            } else {
                                img.scalePercent(percent);
                            }
                            document.add(img);
                        }else{
                            //图片格式后缀不对!
                            info+=file1.getName().toString()+",";
                            result="文件："+info+"，图片格式后缀不对!";
                        }
                    }else{
                        //图片不存在!
                        result="图片不存在!";
                    }
                }

                document.close();
            }
        }else{
            result="图片记录不存在!";
        }
        return result;
    }

    static Document doc =null;
    /**
     * @param imageFolderPath 图片文件夹地址
     * @param pdfPath         PDF文件保存地址
     */
    public static String toPdf(String imageFolderPath, String pdfPath,List dirList) {
        String msg="";
        // 创建文档
        doc = new Document(null, 0, 0, 0, 0);
        try {
            //判断文件夹是否存在
            String pdfStr = pdfPath.substring(0, pdfPath.lastIndexOf("\\"));
            File fileDic = new File(pdfStr);
            if (!fileDic.exists() && !fileDic.isDirectory()) {
                fileDic.mkdirs();
            }
            //判断pdf是否存在，将之前文件删除
            File file1 = new File(pdfPath);
            //boolean a=forceDelete(file1);
            if (file1.exists() && file1.isFile()) {
                if (file1.renameTo(file1)) {
                    file1.delete();
                    //System.out.println("文件未被操作");
                    msg="文件未被操作!";

                } else {
                    //System.out.println("文件正在被操作");
                    msg = "文件正在被操作!";
                }

            }else{
                msg = "文件未被操作!";
            }
            doc.open();

            if(msg.equals("文件未被操作!")){
                // OutputStream fos = new FileOutputStream(pdfPath);
                // 输入流
                OutputStream fos = new FileOutputStream(new File(pdfPath));

                // 获取图片文件夹对象
                File file = new File(imageFolderPath);
                // 写入PDF文档
                PdfWriter.getInstance(doc, fos);
                //imageFolderPath = file.getAbsolutePath() + "\\";
                imgFun(imageFolderPath, file, dirList, doc);

                try {
                    if(fos!=null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
          /*  if (doc.isOpen()) {
                // 关闭文档
                doc.close();
            }*/

        }
        return msg;
    }


    public static void imgFun(String imageFolderPath,File file, List dirList, Document doc){
        doc.open();
        // 图片地址
        String imagePath = null;
        // 读取图片流
        //BufferedImage img = null;
        // 实例化图片
        Image image = null;
        File[] files = file.listFiles();
        if (files.length > 0) {
            // 循环获取图片文件夹内的图片
            try {
                for (File file1 : files) {
                    if (file1.getName().endsWith(".png") || file1.getName().endsWith(".jpg") || file1.getName().endsWith(".gif")
                            || file1.getName().endsWith(".jpeg") || file1.getName().endsWith(".tif")) {

                        //createPic(doc, file1.getPath());

                    }
                    //file.getAbsolutePath().replaceFirst(path, " ");
                    if (file1.isDirectory()) {
                        if (dirList != null && dirList.size() > 0) {
                            if (dirList.indexOf(file1.getName()) != -1) {
                                // System.out.println(file1.getAbsolutePath());
                                imageFolderPath = file1.getAbsolutePath() + "\\";
                                imgFun(imageFolderPath, file1, dirList, doc);

                            }
                        } else {
                            //System.out.println(file1.getAbsolutePath());
                            imageFolderPath = file1.getAbsolutePath() + "\\";
                            imgFun(imageFolderPath, file1, dirList, doc);
                        }
                    }
                }
            } catch(Exception e){
                e.printStackTrace();
            } finally {

                if (doc.isOpen()) {
                    // 关闭文档
                    doc.close();

                }
            }
        }else{
            // System.out.println("空文件夹");
        }


    }


    public static void pdtToPdf(String pdfFolderPath, String pdfPath, List dirList, List pdfList) {
        try {
            // 输入流
//            FileOutputStream fos = new FileOutputStream(pdfPath);
//            // 创建文档
            Document doc = new Document(null, 0, 0, 0, 0);

//            //doc.open();
//            // 写入PDF文档
//            PdfWriter.getInstance(doc, fos);
//
//            // 获取文件夹对象
            File file = new File(pdfFolderPath);
            PDFMergerUtility mergePdf = new PDFMergerUtility();

            //imageFolderPath = file.getAbsolutePath() + "\\";
            pdfFun(pdfFolderPath, file, dirList, pdfList, mergePdf);
            mergePdf.setDestinationFileName(pdfPath);
            mergePdf.mergeDocuments();
            //System.out.print("done");
//            if (doc.isOpen()) {
//                // 关闭文档
//                doc.close();
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void pdfFun(String pdfFolderPath, File file, List dirList,List pdfList, PDFMergerUtility mergePdf) {
        try {
            File[] files = file.listFiles();
            if(file!=null)
                if (files.length > 0) {
                    // 循环获取图片文件夹内的图片
                    for (File file1 : files) {
                        if (file1.getName().endsWith(".pdf")) {
                            //System.out.println(file1.length());
                            if (pdfList != null && pdfList.size() > 0) {
                                //System.out.println("文件名："+file1.getName());
                                if (pdfList.indexOf(file1.getName()) != -1) {

                                }else{
                                    if (file1.length() == 0) {
                                        //file.delete();
                                    } else {
                                        pdfFolderPath = file1.getAbsolutePath();
                                        mergePdf.addSource(pdfFolderPath);
                                    }
                                }
                            }else{
                                if (file1.length() == 0) {
                                    //file.delete();

                                } else {
                                    pdfFolderPath = file1.getAbsolutePath();
                                    mergePdf.addSource(pdfFolderPath);
                                }
                            }

                        }

                        if (file1.isDirectory()) {
                            if (dirList != null && dirList.size() > 0) {
                                if (dirList.indexOf(file1.getName()) != -1) {
                                    pdfFolderPath =  file1.getAbsolutePath() + "\\";
                                    pdfFun(pdfFolderPath, file1, dirList, pdfList, mergePdf);

                                }
                            } else {
                                pdfFolderPath = file1.getAbsolutePath() + "\\";
                                pdfFun(pdfFolderPath, file1, dirList, pdfList, mergePdf);
                            }
                        }

                    }
                } else {
                    System.out.println("空文件夹");
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存文件
     *
     * @param file          保存的文件
     * @param filename      保存文件的名称（参考）
     * @param savepath      文件保存的路径
     * @return boolean (true:保存成功;false:保存失败)
     */
    public static boolean save(File file, String filename, String savepath) {
        filename = filename;
        File f = new File(savepath, filename);
        try {
            FileUtils.copyFile(file, f);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void moveTotherFolders(String startPath, String endPath) {
        try {
            File startFile = new File(startPath);
            File tmpFile = new File(endPath);//获取文件夹路径
            if (!tmpFile.exists()) {//判断文件夹是否创建，没有创建则创建新文件夹
                tmpFile.mkdirs();
            }
            System.out.println(endPath + startFile.getName());
            if (startFile.renameTo(new File(endPath + startFile.getName()))) {
                System.out.println("File is moved successful!");
                //log.info("文件移动成功！文件名：《{}》 目标路径：{}", fileName, endPath);
            } else {
                System.out.println("File is failed to move!");
                //log.info("文件移动失败！文件名：《{}》 起始路径：{}", fileName, startPath);
            }
        } catch (Exception e) {
            //log.info("文件移动异常！文件名：《{}》 起始路径：{}", fileName, startPath);

        }
    }


    /*
     * * 合並pdf文件 * * @param files 要合並文件數組(絕對路徑如{ "e:\\1.pdf", "e:\\2.pdf" ,
     * "e:\\3.pdf"}) * @param newfile
     * 合並後新產生的文件絕對路徑如e:\\temp.pdf,請自己刪除用過後不再用的文件請 * @return boolean
     * 產生成功返回true, 否則返回false
     */

    public static boolean mergePdfFiles2(List<MergePDFItem> files, String newfile) throws Exception {
        boolean retValue = false;

        List<String> tmpFiles = new ArrayList<>();
        try
        {
            for (int i = 0;i<files.size();i++)
            {
                String file = files.get(i).getPdfPath();
                Archive_Detail obj = files.get(i).getdObj();
                boolean isScan = obj.getSource().equals("嘉时扫描系统");
                if(isScan)
                {
                    String tempFile = FileHelper.GetTempFile();
                    PDFHelper.Convert2A4(file, tempFile);
                    tmpFiles.add(tempFile);
                }
                else
                {
                    tmpFiles.add(file);
                }
            }
            PDFHelper.Append(tmpFiles, newfile);
        }
        finally {
            //清理
        }

        return retValue;
    }
    /*
     * * 合並pdf文件 * * @param files 要合並文件數組(絕對路徑如{ "e:\\1.pdf", "e:\\2.pdf" ,
     * "e:\\3.pdf"}) * @param newfile
     * 合並後新產生的文件絕對路徑如e:\\temp.pdf,請自己刪除用過後不再用的文件請 * @return boolean
     * 產生成功返回true, 否則返回false
     */

    public static boolean mergePdfFiles(List files, String newfile) {
        boolean retValue = false;
        Document document = null;

        try {
            System.out.println(files.get(0).toString());
//            // 定义文档对象
//            PDDocument document2 = new PDDocument();
//            // 定义一页，大小A4
//            PDPage page = new PDPage(PDRectangle.A4);
//            document2.addPage(page);
//            document = new Document(new PdfReader(files.get(0).toString()).getPageSize(1));
            document = new Document(PageSize.A4);
            PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(newfile));
            document.open();
            PdfContentByte cb = pdfWriter.getDirectContent();
            for (int i = 0; i < files.size(); i++) {
                String file = files.get(i).toString();
                PdfReader pdfReader = new PdfReader(file);

                // 循环PDF的每一页 pdfWriter.getImportedPage(pdfReader, index) idnex从1开始
                for (int j = 1; j <= pdfReader.getNumberOfPages(); j++) {
                    // 新增一页，不然多页的PDF会重合到一页
                    document.newPage();
                    PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, j);
                    // 计算缩小比例 以最大缩小比例为主
                    // pdfReader.getPageSize(index) index是从1开始不是0
                    float w = PageSize.A4.getWidth() / pdfReader.getPageSize(1).getWidth();
                    float h = PageSize.A4.getHeight() / pdfReader.getPageSize(1).getHeight();
                    float Scale = w > h ? h : w;
                    cb.addTemplate(page, Scale, 0, 0, Scale, 0, 0);
                }
            }
            document.close();

            /*PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
            document.open();
            for (int i = 0; i < files.size(); i++) {
                boolean bol = checkPdfFile(files.get(i).toString());
                System.out.println(bol);
                if(bol) {
                    PdfReader reader = new PdfReader(files.get(i).toString());
                    int n = reader.getNumberOfPages();
                    for (int j = 1; j <= n; j++) {
                        document.newPage();
                        PdfImportedPage page = copy.getImportedPage(reader, j);
                        copy.addPage(page);
                    }
                }else{

                }
            }*/
            retValue = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
        return retValue;
    }
    public static File mulFile2One(List<File> files, String targetPath) throws IOException {
        // pdf合并工具类
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        for (File f : files) {
            boolean bol = checkPdfFile(f.toString());
            if (bol) {
                if (f.exists() && f.isFile()) {
                    // 循环添加要合并的pdf
                    mergePdf.addSource(f);
                }
            }
        }
        // 设置合并生成pdf文件名称
        mergePdf.setDestinationFileName(targetPath);
        // 合并pdf
        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        return new File(targetPath);
    }


    /**
     * 复制单个文件并删除原有的pdf文件
     *
     * @param oldPath String  原文件路径  如：c:/fqf.txt
     * @param newPath String  复制后路径  如：f:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath, String newPath) {
        try {
//           int  bytesum  =  0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) {  //文件存在时
                InputStream inStream = new FileInputStream(oldPath);  //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
//               int  length;
                while ((byteread = inStream.read(buffer)) != -1) {
//                   bytesum  +=  byteread;  //字节数  文件大小
//                   System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        } finally {
            //将之前文件删除
            File file2 = new File(oldPath);
            if (file2.exists() && file2.isFile()) {
                file2.delete();
            }
        }
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String  原文件路径  如：c:/fqf.txt
     * @param newPath String  复制后路径  如：f:/fqf.txt
     * @return boolean
     */
    public static void copyFile2(String oldPath, String newPath) {
        try {
//           int  bytesum  =  0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) {  //文件存在时
                InputStream inStream = new FileInputStream(oldPath);  //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
//               int  length;
                while ((byteread = inStream.read(buffer)) != -1) {
//                   bytesum  +=  byteread;  //字节数  文件大小
//                   System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    public static boolean checkPdfFile(String file) {
        boolean flag1 = false;
        int n = 0;
        try {
            //文件不存在
            File file2 = new File(file);
            if (file2.exists()) {
                //文件损坏
                PdfReader reader = new PdfReader(file);
                Document document = new Document(reader.getPageSize(1));
                document.open();
                n = reader.getNumberOfPages();
                if (n != 0) {
                    flag1 = true;
                }
                document.close();
                //System.out.println("pdf 存在");
            } else {
                //System.out.println("pdf 不存在");
            }

        } catch (IOException e) {
            //System.out.println("文件{path:" + file + "}损坏"+ e.fillInStackTrace());
            return false;
        }
        return flag1;


    }

    private static boolean CheckPdfFiles(List files) {
        boolean flag = false;
        for (int i = 0; i < files.size(); i++) {
            flag = check(files.get(i).toString());
            if (!flag) {
                System.out.println(files.get(i).toString() + "文件损坏");
            }
        }
        return flag;
    }

    /**
     * 利用itext打开pdf文档
     */
    private static boolean check(String file) {
        boolean flag1 = false;
        int n = 0;
        try {
            Document document = new Document(new PdfReader(file).getPageSize(1));
            document.open();
            PdfReader reader = new PdfReader(file);
            n = reader.getNumberOfPages();
            if (n != 0)
                flag1 = true;
            document.close();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return flag1;

    }

    /**
     * 将PDF转化为图片
     * （使用 pdfbox）
     * @param pdfPath PDF对象
     * @param page_end 要转换的页码，发票一般是一页，取第一页
     * @param imgPath 图片保存路径
     * @return
     */
    public static List pdfToImage2(String pdfPath,int page_start,int page_end,String imgPath) {
        String result="";
        List list=new ArrayList();
        Map<String,String> map=null;
        File file = new File(pdfPath);
        if(file.exists()) {
            SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
            String nowTime = format2.format(new Date());
            String filePath =file.getName().substring(0,file.getName().lastIndexOf("."));

            try {
                PDDocument doc = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(doc);
                int pageCount = doc.getNumberOfPages();

                File file2 =new File(imgPath); //此目录保存缩小后的关键图
                if(!file2.exists()){
                    //如果要创建的多级目录不存在才需要创建。
                    file2.mkdirs();
                }
                String fileName="";
                for (int i = pageCount; i>0; i--) {
                    if ((i <=page_end && i>=(page_start))||(page_end==0 &&i==page_start)) {
                        map=new HashMap<>();
                        BufferedImage image = renderer.renderImageWithDPI(i-1, 296);
                        // BufferedImage image = renderer.renderImage(i, 2.5f);
                        fileName=file.getName().substring(0,file.getName().lastIndexOf("."))+"_"+nowTime+"_" + (i)+ "." + DEFAULT_FORMAT;
                        ImageIO.write(image, DEFAULT_FORMAT, new File(imgPath + fileName));
                        map.put("max_picture",imgPath + fileName);
                        map.put("picture_number",i+"");
                        list.add(map);
                        if(i == 1) {
                            doc.removePage(0);
                        }else{
                            doc.removePage(i-1);
                        }
                    }
                }
                doc.save(pdfPath);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            result="文件不存在!";
        }

        return list;
    }

    /**
     * 将PDF转化为图片
     * （使用 pdfbox）
     * @param pdfPath PDF对象
     * @param page_end 要转换的页码，发票一般是一页，取第一页
     * @param imgPath 图片保存路径
     * @return
     */
    public static List pdfToImage(String pdfPath,int page_start,int page_end,String imgPath) {
        String result="";
        List list=new ArrayList();
        Map<String,String> map=null;
        File file = new File(pdfPath);
        if(file.exists()) {
            SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
            String nowTime = format2.format(new Date());
            String filePath =file.getName().substring(0,file.getName().lastIndexOf("."));

            try {
                PDDocument doc = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(doc);
                int pageCount = doc.getNumberOfPages();


                String fileName="";
                String oleFileName=file.getName().substring(0,file.getName().lastIndexOf("."));
                for (int i = pageCount; i>0; i--) {
                    if ((i <=page_end && i>=(page_start))||(page_end==0 &&i==page_start)) {
                        map=new HashMap<>();
                        BufferedImage image = renderer.renderImageWithDPI(i-1, 296);
                        // BufferedImage image = renderer.renderImage(i, 2.5f);
                        File file2 =new File(imgPath+oleFileName+"\\"); //此目录保存缩小后的关键图
                        if(!file2.exists()){
                            //如果要创建的多级目录不存在才需要创建。
                            file2.mkdirs();
                        }
                        fileName=oleFileName+"_"+nowTime+"_" + (i)+ "." + DEFAULT_FORMAT;
                        ImageIO.write(image, DEFAULT_FORMAT, new File(imgPath+oleFileName+"\\" + fileName));
                        map.put("max_picture",imgPath+oleFileName+"\\" + fileName);
                        map.put("picture_number",i+"");
                        list.add(map);
                        if(i == 1) {
                            doc.removePage(0);
                        }else {
                            doc.removePage(i-1);
                        }
                    }
                }
                doc.save(pdfPath);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            result="文件不存在!";
        }

        return list;
    }

    public static void delete(File file) {
        if(!file.exists()) return;
        if(file.isFile() || file.list()==null) {
            file.delete();
            // System.out.println("删除了"+file.getName());
        }else {
            File[] files = file.listFiles();
            for(File a:files) {
                delete(a);
            }
            file.delete();
            // System.out.println("删除了"+file.getName());
        }

    }


    /**
     * @description
     *	针对页码生成的PDF事件监听
     * @author TianwYam
     * @date 2019年12月28日下午8:51:08
     */
    public static class PageNumPdfPageEvent extends com.itextpdf.text.pdf.PdfPageEventHelper {

        @Override
        public void onEndPage(com.itextpdf.text.pdf.PdfWriter writer, com.itextpdf.text.Document document) {

            try {
                // PDF文档内容
                com.itextpdf.text.pdf.PdfContentByte pdfContent = writer.getDirectContent();
                pdfContent.saveState();
                pdfContent.beginText();
                int footerFontSize = 14 ;

                // 解决页码中文无法显示 或者 显示为乱码的问题
                // 但是必须引入jar包 itext-asian-5.2.0.jar
                com.itextpdf.text.pdf.BaseFont baseFont = com.itextpdf.text.pdf.BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
                com.itextpdf.text.Font fontDetail = new com.itextpdf.text.Font(baseFont, footerFontSize, com.itextpdf.text.Font.NORMAL);

                pdfContent.setFontAndSize(baseFont, footerFontSize);

                // 页脚的页码 展示
                String footerNum = String.format("第%d页", writer.getPageNumber());
                Phrase phrase = new Phrase(footerNum, fontDetail);

                // 页码的 横轴 坐标 居中
                float x = ( document.left() + document.right() ) / 2 ;
                // 页码的 纵轴 坐标
                float y = document.bottom(-10) ;
                // 添加文本内容，进行展示页码
                com.itextpdf.text.pdf.ColumnText.showTextAligned(pdfContent, Element.ALIGN_CENTER, phrase, x, y, 0);

                pdfContent.endText();
                pdfContent.restoreState();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * @description
     *	给PDF文件添加页码
     * @author TianwYam
     * @date 2019年12月28日下午8:48:55
     * @param orgPdfPath 源PDF文件路径
     * @param outputPdfPath 加了页码的PDF文件路径
     * @return 返回添加了页码的PDF文件路径
     */
    public static String addPageNum (String orgPdfPath, String outputPdfPath) {
        try (
                // 输出文件 流
                FileOutputStream fos = new FileOutputStream(outputPdfPath);){

            // 新建文档，默认A4大小
            com.itextpdf.text.Document document = new com.itextpdf.text.Document(com.itextpdf.text.PageSize.A4);
            com.itextpdf.text.pdf.PdfWriter writer = com.itextpdf.text.pdf.PdfWriter.getInstance(document, fos);
            // 设置页面监听事件，必须在open方法前
            writer.setPageEvent(new PageNumPdfPageEvent());
            document.open();

            // PDF内容体
            com.itextpdf.text.pdf.PdfContentByte pdfContent = writer.getDirectContent();
            // 读取 源PDF文件，进行一页一页复制，才能触发 添加页码的  页面监听事件
            com.itextpdf.text.pdf.PdfReader reader = new com.itextpdf.text.pdf.PdfReader(orgPdfPath);
            // 获取 源文件总页数
            int num = reader.getNumberOfPages();
           // System.out.println("总页数：" + num);
            // 页面数是从1开始的
            for (int i = 1; i <= num; i++) {
                document.newPage();
                // 设置空页码进行展示
                writer.setPageEmpty(false);
                com.itextpdf.text.pdf.PdfImportedPage page = writer.getImportedPage(reader, i);
                // 复制好的页面，添加到内容去，触发事件监听
                pdfContent.addTemplate(page, 0, 0);
            }

            document.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return outputPdfPath ;
    }




    public static void main(String[] args) throws IOException, DocumentException {
        String pdfFile = String.valueOf(System.currentTimeMillis());
        //读取指定路径下的文件名和目录名
        List list = new ArrayList();
        list.add("45646546");

        //图片转PDF(病案号文件夹+类别文件夹)
        // String str=toPdf("C:\\Users\\Administrator\\Desktop\\测试\\uploadImage\\", "C:\\Users\\Administrator\\Desktop\\测试\\" +  "123.pdf", list);
        // System.out.println(str);
        //多个pdf合成一个
        //pdtToPdf("D:\\project_js\\EMR_Medical_Record\\src\\main\\webapp\\static\\img\\pdfFiles\\1333ad3c4d6448c89372835dbad3c364\\", "D:\\project_js\\EMR_Medical_Record\\src\\main\\webapp\\static\\img\\pdfFiles\\typesPdf\\"+ pdfFile+".pdf", list);

        //图片移动
        //moveTotherFolders("D:\\project_js\\EMR_Medical_Record\\src\\main\\webapp\\static\\img\\uploads\\1333ad3c4d6448c89372835dbad3c364\\HC3SL2HENH348M8X619PMCA7GC5R3125\\2019071905226021565006922724小程序界面.png","D:\\project_js\\EMR_Medical_Record\\src\\main\\webapp\\static\\img\\uploads\\1333ad3c4d6448c89372835dbad3c364\\SDV1QEHUPQRQ8GXJE4RQH0FGAS1V7HM0\\");
        //moveTotherFolders("D:\\project_js\\EMR_Medical_Record\\src\\main\\webapp/static\\img\\uploads\\1333ad3c4d6448c89372835dbad3c364\\HC3SL2HENH348M8X619PMCA7GC5R3125\\2019071905226021565064554400fw.jpg", "D:\\project_js\\EMR_Medical_Record\\src\\main\\webapp\\static\\img\\uploads\\1333ad3c4d6448c89372835dbad3c364\\3\\");
        List list1 = new ArrayList();
        list.add("C:\\Users\\HIPAA\\Desktop\\测试\\ttt.pdf");
        list.add("C:\\Users\\HIPAA\\Desktop\\测试\\sss.pdf");
        //String[] files = {"C:\\Users\\Administrator\\Desktop\\新建文件夹\\ttt.pdf", "C:\\Users\\Administrator\\Desktop\\新建文件夹\\sss.pdf"};
        String savepath = "C:\\Users\\HIPAA\\Desktop\\测试\\temp.pdf";
        //mergePdfFiles(list1, savepath);
        //mergePdfFiles(list1, savepath);
       // PrintToPdfUtil.copyFile2("C:\\Users\\Administrator\\Desktop\\test\\delPicImg\\新建文件夹\\ttt.pdf", "C:\\Users\\Administrator\\Desktop\\test\\delPicImg\\新建文件夹\\3.pdf");

        List pdfList = new ArrayList();
        //pdfList.add("C:\\Users\\Administrator\\Desktop\\测试\\ttt.pdf");
        pdfList.add("C:\\Users\\HIPAA\\Desktop\\测试\\sss7.pdf");
        pdfList.add("C:\\Users\\HIPAA\\Desktop\\测试\\15511.pdf");
        //mergePdfFiles(pdfList, "C:\\Users\\Administrator\\Desktop\\测试\\合成.pdf");

        ArrayList<String> pdffiles = new ArrayList<String>();
        //pdffiles.add("C:\\Users\\Administrator\\Desktop\\测试\\15511.pdf");
        // pdffiles.add("D:\\project\\yingde\\EMR_Medical_Record\\src\\main\\webapp\\static\\img\\pdfFiles\\0f6e6941028c44b8b8ea070f27480416\\HC3SL2HENH348M8X619PMCA7GC5R3125\\HC3SL2HENH348M8X619PMCA7GC5R3125.pdf");
        //boolean checkPdf=CheckPdfFiles(pdffiles);

        //System.out.println(checkPdf);

        //判断文件是否损坏
        //boolean bol=checkPdfFile("D:\\project\\yingde\\EMR_Medical_Record\\src\\main\\webapp\\static\\img\\pdfFiles\\0f6e6941028c44b8b8ea070f27480416\\HC3SL2HENH348M8X619PMCA7GC5R3125\\HC3SL2HENH348M8X619PMCA7GC5R3125.pdf");
        //System.out.println(bol);

        List<File> files = new ArrayList<File>();
        pdffiles.add("C:\\Users\\Administrator\\Desktop\\测试\\15511.pdf");
        pdffiles.add("C:\\Users\\Administrator\\Desktop\\测试\\153333511.pdf");
        //files.add(new File("C:\\Users\\Administrator\\Desktop\\测试\\123.pdf"));
        //files.add(new File("C:\\Users\\Administrator\\Desktop\\测试\\sss.pdf"));
        //files.add(new File("C:\\Users\\Administrator\\Desktop\\测试\\ttt333.pdf"));
        //File f = mulFile2One(files, "C:\\Users\\Administrator\\Desktop\\测试\\mul2one.pdf");

        //复制pdf文件
        /*File file=new File("C:\\Users\\Administrator\\Desktop\\images\\报表工具v2.4操作手册文档.pdf");
        save(file, "cc.pdf", "C:\\Users\\Administrator\\Desktop\\images");*/

        //String fileName="C:\\Users\\HIPAA\\Desktop\\测试\\sss7.pdf";
       // fileName = fileName.substring(fileName.lastIndexOf("\\")+1).replace(".pdf","");
       // System.out.println("方法二：fileName = " + fileName);

        List<Emr_Picture> list2 = new ArrayList();
        Emr_Picture pic=new Emr_Picture();
        pic.setMaxPicture("D:\\test\\uploadImage\\a490ca0b-879f-4ae4-9238-33c44e5fda99\\3\\202012931178716189095653488.jpg");
        list2.add(pic);
        pic=new Emr_Picture();
        pic.setMaxPicture("D:\\test\\uploadImage\\a490ca0b-879f-4ae4-9238-33c44e5fda99\\3\\2020129311787161890956595411.jpg");
        list2.add(pic);
        String pdfPath="D:\\test\\uploadImage\\a490ca0b-879f-4ae4-9238-33c44e5fda99\\3\\3.pdf";
        String fileName=imgsListTopdf(pdfPath,list2);
        System.out.println("合成pdf: " + fileName);

    }




}



