package com.emr.util;

import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.ImageType;
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.*;

public class Main {
    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";

    /***
     * @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);

                }


            }
        }
    }

    /**
     * 将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());
        }

    }


    /**
     * 插入单张图片
     *
     * @param inputPdfPath  要操作的pdf路径 C:\\Users\\aaa\\Desktop\\20181011114615447qp.pdf
     * @param outputPdfPath 输出的pdf路径
     * @param imgPath       添加的图片路径 E:\\code\\qrcode.png
     * @param pageNum     页数位置
     * @return
     */
    public static int insertImgToPdf(String inputPdfPath, String outputPdfPath, String imgPath,int pageNum) {
        File file = new File(inputPdfPath);
        File file2 = new File(outputPdfPath);
        int bol=1;
        if (file.exists()) {
            try {
                PDDocument doc = PDDocument.load(file);
                PDDocument doc2 = PDDocument.load(file2);
                PDFRenderer renderer = new PDFRenderer(doc);
                int pageCount = doc.getNumberOfPages();


                doc.save(outputPdfPath);
                for (int i = pageCount-1; i >= 0; i--) {
                    PDPage myPage = doc.getPage(i);
                    Image image = Image.getInstance(imgPath);
                    PDImageXObject pdImage  = PDImageXObject.createFromFile(imgPath, doc2);

                    int iw = pdImage.getWidth();
                    int ih = pdImage.getHeight();
                    float offset = 20f;
                    try (PDPageContentStream cont = new PDPageContentStream(doc2, myPage)) {
                        cont.drawImage(pdImage, offset, offset, iw, ih);

                    }

                    if (i==pageNum || i==(pageNum-1)) {
                        BufferedImage image2 = renderer.renderImageWithDPI(i - 1, 296);



                    }
                }
                doc2.save(outputPdfPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return bol;
    }




    public static void main(String[] args) throws IOException {
        //读取指定路径下的文件名和目录名
      /*  List dirList = new ArrayList();
        dirList.add("3");
        //dirList.add("17");
       try {
            image2pdf("C:\\Users\\Administrator\\Desktop\\文档\\",dirList);
        } catch (DocumentException e) {
            e.printStackTrace();
        }*/


        /*File file=new File("C:\\Users\\Administrator\\Desktop\\文档\\微服.png");
        //将原文件更改为f:\a\b.xlsx，其中路径是必要的。注意
        //file.renameTo(new File("C:\\Users\\Administrator\\Desktop\\文档\\微服1.png"));
        System.out.println("===="+file.getPath().substring(0,file.getPath().lastIndexOf("\\")+1));
        String a="C:\\Users\\Administrator\\Desktop\\文档\\微服.png";
        System.out.println("===="+a.substring(a.lastIndexOf("\\")+1,a.length()));*/
/*
        FileOutputStream fos = null;
        try {
            Document doc = new Document(null, 0, 0, 0, 0);
            Image img = null;

            img = Image.getInstance("C:\\Users\\Administrator\\Desktop\\test\\uploadImage\\11111111111133333\\3\\202101139226821616740775027.png");

            float documentWidth = doc.getPageSize().getWidth() - doc.leftMargin() - doc.rightMargin();
            float documentHeight = documentWidth / 580 * 320;// 重新设置宽高
            img.scaleAbsolute(documentWidth, documentHeight);// 重新设置宽高
            doc.add(img);
            doc.close();
            // 输入流
            fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test\\uploadImage\\11111111111133333");
            // 写入PDF文档
            PdfWriter.getInstance(doc, fos);
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();

        }*/

        //删除pdf页码保存图片
        String pdfPath="C:\\Users\\Administrator\\Desktop\\test\\delPicImg\\331.pdf";
        int page_start=1;
        int page_end=3;
        String imgPath="C:\\Users\\Administrator\\Desktop\\test\\delPicImg\\";
        List list=pdfToImage(pdfPath,page_start,page_end,imgPath);
        System.out.println(list.toString());

        //删除文件夹的和所有文件
        //File file = new File("C:\\Users\\Administrator\\Desktop\\test\\delPicImg\\202103311721593");
        //delete(file);
        // 模板文件路径
        String templatePath = "C:\\Users\\Administrator\\Desktop\\test\\delPicImg\\3.pdf";
       // 生成的文件路径
        String targetPath = "C:\\Users\\Administrator\\Desktop\\test\\delPicImg\\target.pdf";
        // 图片路径
        String fieldName = "C:\\Users\\Administrator\\Desktop\\test\\delPicImg\\2.jpg";
        // 页数
        int pageNum=0;
        String imagePath = "C:\\Users\\Administrator\\Desktop\\test\\delPicImg\\2.jpg";
        //insertImgToPdf(templatePath, targetPath, fieldName,pageNum);



    }



}
