package com.emr.util;

import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.*;
import com.lowagie.text.pdf.codec.TiffImage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/6/6 9:07
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/6/6 9:07
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class Jpg2PdfUtil {
    static Logger  logger = LoggerFactory.getLogger(Jpg2PdfUtil.class);
    public static void imageToPdf(HttpServletResponse response, List<String> filePaths, String pdfName) throws Exception{
        // 实例化图牿
        Image image = null;
        pdfName = java.net.URLEncoder.encode(pdfName, "UTF-8");
        Document doc = new Document();
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf"); // word格式
        response.setHeader("Content-Disposition", "attachment; filename=" + pdfName+ "("+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +").pdf");
        PdfWriter writer = PdfWriter.getInstance(doc, response.getOutputStream());
        // 开启文桿
        doc.open();
        try {
            for (String filePath : filePaths) {
                File file1 = new File(filePath);
                if(file1.exists()){
                    if (file1.getName().endsWith(".tif") || file1.getName().endsWith(".tiff")) {
                        Object localObject1 = null;
                        Object localObject2 = null;
                        URL paramURL = Utilities.toURL(filePath);
                        try {
                            if (paramURL.getProtocol().equals("file")) {
                                localObject2 = paramURL.getFile();
                                localObject2 = Utilities
                                        .unEscapeURL((String) localObject2);
                                localObject1 = new RandomAccessFileOrArray(
                                        (String) localObject2);
                            } else {
                                localObject1 = new RandomAccessFileOrArray(paramURL);
                            }

                            int pageNums = TiffImage
                                    .getNumberOfPages((RandomAccessFileOrArray) localObject1);
                            if (pageNums > 0) {
                                for (int i = 1; i <= pageNums; i++) {
                                    localObject2 = TiffImage.getTiffImage(
                                            (RandomAccessFileOrArray) localObject1, i);
                                    image = (Image) localObject2;
                                }
                            }
                            if (localObject1 != null)
                                ((RandomAccessFileOrArray) localObject1).close();

                        } finally {
                            if (localObject1 != null)
                                ((RandomAccessFileOrArray) localObject1).close();
                        }
                    }else if (file1.getName().endsWith(".png")
                            || file1.getName().endsWith(".jpg")
                            || file1.getName().endsWith(".gif")
                            || file1.getName().endsWith(".jpeg")
                    ) {
                        // 实例化图牿
                        image = Image.getInstance(filePath);
                    }
                    // 获得图片的高庿
                    float heigth = image.getHeight();
                    float width = image.getWidth();
                    // 合理压缩，h>w，按w压缩，否则按w压缩
                    int percent = getPercent(heigth, width);

                    // 设置图片居中显示
                    //image.setAlignment(Image.MIDDLE);
                    image.setAlignment(Image.ALIGN_CENTER);
                    //image.scaleAbsolute(500, 400);
                    // 按百分比显示图片的比便
                    if (width > 1024 || heigth > 786) {
                        image.scalePercent(percent+5);
                    }
                    PdfContentByte canvas = writer.getDirectContent();
                    //pdf文档中中文字体的设置，注意一定要添加iTextAsian.jar包
                    BaseFont bfChinese = BaseFont.createFont("STSong-Light",
                            "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
                    Font fontChinese = new Font(bfChinese, 50, Font.NORMAL,Color.blue);
                    Phrase phrase = new Phrase("老客户看黑科技好客户客户客户客户客户客户看黑科技",fontChinese);
                    ColumnText.showTextAligned(
                            canvas, Element.ALIGN_UNDEFINED, phrase, 200, 200, 50);
                    Image image1 = null;
                    image1 = Image.getInstance("D:\\出差准备文档\\pdf\\9d17f073c61adfaf79438401bc6ffb7.jpg");
                        //位置
                    image1.setAbsolutePosition(200, 200);
                        // 设置图片的显示大小
                    image1.scaleToFit(200, 200);
                    canvas.addImage(image1);
                    doc.add(image);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (doc.isOpen()) {
                doc.close();
            }
        }
    }


    private static Document openDocument(HttpServletResponse response,String pdfName) throws Exception{
        Document doc = new Document();
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf"); // word格式
        response.setHeader("Content-Disposition", "attachment; filename=" + pdfName+ "("+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +").pdf");
        // 定义输出文件的位罿
        PdfWriter.getInstance(doc,response.getOutputStream());
        // 开启文桿
        doc.open();
        return doc;
    }


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

    public static void mulFile2One(HttpServletResponse response,List<String> files,String waterMarkName) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //遍历删除,除去损坏，文件不存在，抛异常就是空白页
        Iterator<String> iterator = files.iterator();
        long start = System.currentTimeMillis();
        while (iterator.hasNext()) {
            String fileStr = iterator.next();
            File file = new File(fileStr);
            if(file.isFile()){
                boolean flag = false;
                flag = check(fileStr);
                if(!flag){
                    iterator.remove();
                    System.out.println(fmt.format(new Date())+":"+file+"文件损坏");
                }
            }else{
                iterator.remove();
                System.out.println(fmt.format(new Date())+":"+file+"文件不存在");
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("验证并移除无效pdf的时间："+(end-start)/1000.0+"s");
        Document document = null;
        if(null != files && !files.isEmpty()){
            try {
                response.reset();
                document = new Document(new PdfReader(files.get(0)).getPageSize(1));
                PdfCopy copy = new PdfCopy(document,response.getOutputStream());
                document.open();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                for (int i = 0; i < files.size(); i++) {
                    //判断是否加水印
                    if(StringUtils.isNotBlank(waterMarkName)){
                        setWatermark(bos,files.get(i), waterMarkName, null);
                    }
                    PdfReader reader = new PdfReader(files.get(i));
                    int n = reader.getNumberOfPages();
                    for (int j = 1; j <= n; j++) {
                        document.newPage();
                        PdfImportedPage page = null;
                        if(StringUtils.isNotBlank(waterMarkName)){
                            page = copy.getImportedPage(new PdfReader(bos.toByteArray()), j);
                        }else{
                            page = copy.getImportedPage(reader, j);
                        }
                        copy.addPage(page);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                document.close();
            }

        }
    }


    //加水印
    private static void setWatermark(ByteArrayOutputStream bos, String input, String waterMarkName, String imgPath)
            throws Exception{
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, bos);
        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        PdfGState gs = new PdfGState();
        for (int i = 1; i < total; i++) {
            //content = stamper.getOverContent(i);// 在内容上方加水印
            content = stamper.getUnderContent(i);
            //加文字水印
            if(StringUtils.isNotBlank(waterMarkName)) {
                gs.setFillOpacity(0.3f);
                gs.setStrokeOpacity(0.3f);
                content.setGState(gs);
                content.beginText();
                content.setColorFill(Color.LIGHT_GRAY);
                content.setFontAndSize(base, 50);
                content.setTextMatrix(70, 200);
                content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 600, 40);
                content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 200, 40);
                content.endText();
            }
            if(StringUtils.isNotBlank(imgPath)){
                Image image = Image.getInstance(imgPath);
                image.setAbsolutePosition(200, 206); // set the first background
                image.scaleToFit(200, 200);
                content.addImage(image);
            }
            content.setColorFill(Color.BLACK);
            content.setFontAndSize(base, 8);
        }
        stamper.close();
    }
    /**
     * 在不改变图片形状的同时，判断，如果h>w，则按h压缩，否则在w>h或w=h的情况下，按宽度压缩
     * @param h
     * @param w
     * @return
     */
    public static int getPercent(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        if (h > w) {
            p2 = 210 / h * 279;
        } else {
            p2 = 210 / w * 279;
        }
        p = Math.round(p2);
        return p;
    }

/*
    */
/**
     * 添加图片和文字水印
     *
     * @param srcFile 待加水印文件
     * @param destFile 加水印后存放地址
     * @param upOrUnder 加水印后存放地址
     * @param transparent 加水印透明度
     * @param text 加水印的文本内容
     * @param textWidth 文字横坐标
     * @param textHeight 文字纵坐标
     * @param textColor 文字颜色
     * @param textSize 文字字号
     * @param textRotation 文字旋转角度
     * @param imgFile 加水印图片文件
     * @param imgWidth 图片宽
     * @param imgHeight 图片高
     * @param imgX 图片横坐标
     * @param imgY 图片纵坐标
     * @throws IOException
     * @throws DocumentException
     *//*

    public static void addWaterMark(String srcFile, String destFile,int upOrUnder,float transparent, String text, int textWidth, int textHeight,
                                    String textColor,int textSize,int textRotation,
                                    String imgFile, int imgWidth, int imgHeight,int imgX,int imgY) throws IOException, DocumentException {
        // 待加水印的文件
        PdfReader reader = new PdfReader(srcFile);
        // 加完水印的文件
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
        // 设置字体
        BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        // PDF总页数
        int total = reader.getNumberOfPages() + 1;
        // 循环对每页插入水印
        PdfContentByte content;
        PdfGState gs = new PdfGState();
        for (int i = 1; i < total; i++) {
            //upOrUnder = 1为在文本之上
            if(upOrUnder == 1){
                // 水印在之前文本之上
                content = stamper.getOverContent(i);
            }else{
                // 水印在文本之下
                content = stamper.getUnderContent(i);
            }
            //设置填充字体不透明度为0.2f
            gs.setFillOpacity(transparent);
            content.setGState(gs);
            // 图片水印
            if (imgFile != null) {
                Image image = null;
                if (imgFile != null) {
                    image = Image.getInstance(imgFile);
                    //位置
                    image.setAbsolutePosition(imgX, imgY);
                    // 设置图片的显示大小
                    image.scaleToFit(imgWidth, imgHeight);
                }
                content.addImage(image);
            }
            // 文字水印
            if (text != null) {
                content.beginText();
                // 设置颜色 默认为蓝色
                content.setColorFill(Color.BLUE);
                // 设置字体及字号
                content.setFontAndSize(font, textSize);
                // 设置起始位置
                content.setTextMatrix(textWidth, textHeight);
                // 中间水印
                content.showTextAligned(Element.ALIGN_LEFT, text, textWidth, textHeight, textRotation);
                // 底部水印
                */
/*for (int k = 0; k < text.length(); k++) {
                    // 距离底边的距离
                    content.setTextRise(10);
                    // 将char转成字符串
                    content.showText(String.valueOf(text.charAt(k)));
                }*//*

                content.endText();
            }
        }
        stamper.close();
    }
*/

}
