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.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.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);
                    phrase.clear();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (doc.isOpen()) {
                doc.close();
            }
            writer.flush();
            writer.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;
    }
}
