package com.emr.util;

import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
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 img2PdfUtil {
    final private static float A4_weight = 595; //标准A4的宽
    final private static float A4_height = 842; //标准A4的高

    public static void imageToPdf(HttpServletResponse response, List<String> filePaths, String pdfName, EmrPdfWaterSet pdfWaterSet,EmrPdfWaterSet pdfWaterSet1) {
        Document document = new Document(PageSize.A4, 0, 0, 0, 0); //创建文档容器
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //是否启用水印
        Short effective = pdfWaterSet.getEffective();
        Short isImg = pdfWaterSet.getIsImg();
        try {
            if (effective == 1 || isImg == 1) {
                PdfWriter.getInstance(document, bos); //创建编写器（PDF类型）
            } else {
                PdfWriter.getInstance(document, response.getOutputStream()); //创建编写器（PDF类型）
            }
            pdfName = java.net.URLEncoder.encode(pdfName, "UTF-8");
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("x-www-form-urlencoded"); // word格式
            response.setHeader("Content-Disposition", "attachment; filename=" + pdfName + ".pdf");
            //图片合成pdf
            imgToPdf(document, filePaths);
            if (effective == 1 || isImg == 1) {
                addWaterMark(bos, response, pdfWaterSet.getUpOrUnder(), pdfWaterSet.getTransparent(),
                        pdfWaterSet.getText(), pdfWaterSet.getTextX(), pdfWaterSet.getTextY(),
                        pdfWaterSet.getTextColor(), pdfWaterSet.getTextSize(), pdfWaterSet.getTextRotation(),
                        pdfWaterSet.getEffective(), pdfWaterSet.getIsImg(), pdfWaterSet.getImgFile(), pdfWaterSet.getImgWidth(),
                        pdfWaterSet.getImgHeight(), pdfWaterSet.getImgX(), pdfWaterSet.getImgY(),pdfWaterSet1.getText());
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        } finally {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            document.close();
        }
    }





    public static void imageToPdfUserEffective(HttpServletResponse response, List<String> filePaths, String pdfName, EmrPdfWaterSet pdfWaterSet) {
        Document document = new Document(PageSize.A4, 0, 0, 0, 0); //创建文档容器
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //是否启用水印
        Short effective = pdfWaterSet.getEffective();
        Short isImg = pdfWaterSet.getIsImg();
        try {
            if (effective == 1 || isImg == 1) {
                PdfWriter.getInstance(document, bos); //创建编写器（PDF类型）
            } else {
                PdfWriter.getInstance(document, response.getOutputStream()); //创建编写器（PDF类型）
            }
            pdfName = java.net.URLEncoder.encode(pdfName, "UTF-8");
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("x-www-form-urlencoded"); // word格式
            response.setHeader("Content-Disposition", "attachment; filename=" + pdfName + ".pdf");
            //图片合成pdf
            imgToPdf(document, filePaths);
            if (effective == 1 || isImg == 1) {
                addWaterMark(bos, response, pdfWaterSet.getUpOrUnder(), pdfWaterSet.getTransparent(),
                        pdfWaterSet.getText(), pdfWaterSet.getTextX(), pdfWaterSet.getTextY(),
                        pdfWaterSet.getTextColor(), pdfWaterSet.getTextSize(), pdfWaterSet.getTextRotation(),
                        pdfWaterSet.getEffective(), pdfWaterSet.getIsImg(), pdfWaterSet.getImgFile(), pdfWaterSet.getImgWidth(),
                        pdfWaterSet.getImgHeight(), pdfWaterSet.getImgX(), pdfWaterSet.getImgY());
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        } finally {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            document.close();
        }
    }

    public static void imageToPdf2(HttpServletResponse response, String filePath, String targetPath, EmrPdfWaterSet pdfWaterSet) {
        Document document = new Document(PageSize.A4, 30, 30, 30, 30); //创建文档容器
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        OutputStream out = null;
        //是否启用水印
        Short effective = pdfWaterSet.getEffective();
        Short isImg = pdfWaterSet.getIsImg();
        try {
            if (effective == 1 || isImg == 1) {
                PdfWriter.getInstance(document, bos); //创建编写器（PDF类型）
            } else {
                out = new FileOutputStream(filePath);
                PdfWriter.getInstance(document, out); //创建编写器（PDF类型）
            }
            //图片合成pdf
            List<String> files = new ArrayList<>();
            files.add(filePath);
            imgToPdf(document, files);
            if (effective == 1 || isImg == 1) {
                addWaterMarkFont(bos, pdfWaterSet.getUpOrUnder(), pdfWaterSet.getTransparent(),
                        pdfWaterSet.getText(), pdfWaterSet.getTextX(), pdfWaterSet.getTextY(),
                        pdfWaterSet.getTextColor(), pdfWaterSet.getTextSize(), pdfWaterSet.getTextRotation(),
                        pdfWaterSet.getEffective(), pdfWaterSet.getIsImg(), pdfWaterSet.getImgFile(), pdfWaterSet.getImgWidth(),
                        pdfWaterSet.getImgHeight(), pdfWaterSet.getImgX(), pdfWaterSet.getImgY(), targetPath);
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        } finally {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            document.close();
        }
    }

    public static void imageToPdfFont(List<String> filePaths, EmrPdfWaterSet pdfWaterSet, String fileOutPath) {
        Document document = new Document(PageSize.A4, 30, 30, 30, 30); //创建文档容器
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        OutputStream out = null;
        //是否启用水印
        Short effective = pdfWaterSet.getEffective();
        Short isImg = pdfWaterSet.getIsImg();
        try {
            if (effective == 1 || isImg == 1) {
                PdfWriter.getInstance(document, bos); //创建编写器（PDF类型）
            } else {
                out = new FileOutputStream(fileOutPath);
                PdfWriter.getInstance(document, out); //创建编写器（PDF类型）
            }
            //图片合成pdf
            imgToPdf(document, filePaths);
            if (effective == 1 || isImg == 1) {
                addWaterMarkFont(bos, pdfWaterSet.getUpOrUnder(), pdfWaterSet.getTransparent(),
                        pdfWaterSet.getText(), pdfWaterSet.getTextX(), pdfWaterSet.getTextY(),
                        pdfWaterSet.getTextColor(), pdfWaterSet.getTextSize(), pdfWaterSet.getTextRotation(),
                        pdfWaterSet.getEffective(), pdfWaterSet.getIsImg(), pdfWaterSet.getImgFile(), pdfWaterSet.getImgWidth(),
                        pdfWaterSet.getImgHeight(), pdfWaterSet.getImgX(), pdfWaterSet.getImgY(), fileOutPath);
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                    out.close();
                }
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            document.close();
        }
    }

    //脐血库下载批量
    public static void imageToPdfToBuffOut(ByteArrayOutputStream bos, List<String> filePaths, EmrPdfWaterSet pdfWaterSet) throws Exception {
        // 实例化图牿
        Document document = new Document(PageSize.A4, 30, 30, 30, 30); //创建文档容器
        //是否启用水印
        PdfWriter.getInstance(document, bos);
        try {
            //图片合成pdf
            imgToPdf(document, filePaths);
            //是否启用水印
            Short effective = pdfWaterSet.getDownloadEffective();
            Short isImg = pdfWaterSet.getDownloadIsImg();
            if (effective == 1 || isImg == 1) {
                addWaterMark(bos, null, pdfWaterSet.getUpOrUnder(), pdfWaterSet.getTransparent(),
                        pdfWaterSet.getText(), pdfWaterSet.getTextX(), pdfWaterSet.getTextY(),
                        pdfWaterSet.getTextColor(), pdfWaterSet.getTextSize(), pdfWaterSet.getTextRotation(),
                        effective, isImg, pdfWaterSet.getImgFile(), pdfWaterSet.getImgWidth(),
                        pdfWaterSet.getImgHeight(), pdfWaterSet.getImgX(), pdfWaterSet.getImgY());
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        } finally {
            document.close();
        }
    }

    public static String addWatermarkPic1(File srcImgFile, EmrPdfWaterSet pdfWaterSet, String outPath,EmrPdfWaterSet pdfWaterSet1) {
        java.awt.Image srcImg = null;
        BufferedImage bufImg = null;
        Graphics2D g = null;
        try {
            srcImg = ImageIO.read(new FileInputStream(srcImgFile));
            /*if(null == srcImg){
                IIORegistry registry = IIORegistry.getDefaultInstance();
                registry.registerServiceProvider(new com.twelvemonkeys.imageio.plugins.tiff.TIFFImageWriterSpi());
                registry.registerServiceProvider(new com.twelvemonkeys.imageio.plugins.tiff.TIFFImageReaderSpi());
                srcImg = ImageIO.read(new FileInputStream(srcImgFile));
            }*/
            //System.out.println("读取图片"+(end-start)/1000.0+"s");
            int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);//获取图片的高
            // 加水印
            bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Font font = new Font("STSong-Light", Font.ITALIC, pdfWaterSet.getTextSize() * 4);//水印字体，大小
            g = bufImg.createGraphics();//得到画笔
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            //System.out.println("画图片"+(end1-start1)/1000.0+"s");
            //判断是否加水印
            Short effective = pdfWaterSet.getEffective();
            Short isImg = pdfWaterSet.getIsImg();
            if (effective == 1 || isImg == 1) {
                Color color = toColorFromString(pdfWaterSet.getTextColor());
                int degree = 0 - pdfWaterSet.getTextRotation();//设置水印文字的旋转角度
                float alpha = pdfWaterSet.getTransparent();//设置水印透明度 默认为1.0  值越小颜色越浅
                g.setColor(color); //设置水印颜色
                g.setFont(font);              //设置字体
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));//设置水印文字透明度
                g.rotate(Math.toRadians(degree), (double) bufImg.getWidth(), (double) bufImg.getHeight());//设置水印旋转
                g.drawString(pdfWaterSet.getText(), srcImg.getWidth(null) / 2 + pdfWaterSet.getTextX() , srcImg.getHeight(null) / 2 + (pdfWaterSet.getTextY() - 300));//画出水印,并设置水印位置
                g.drawString(pdfWaterSet1.getText(), srcImg.getWidth(null) / 2 + pdfWaterSet.getTextX() , srcImg.getHeight(null) / 2 + (pdfWaterSet.getTextY() -100));//画出水印,并设置水印位置
                //System.out.println("画文字图片"+(end2-start2)/1000.0+"s");
            }
            //ByteArrayInputStream fis = new ByteArrayInputStream(imageToByteArr);//创建输入流对象
            if (!new File(outPath).exists()) {
                ImageIO.write(bufImg, "jpg", new File(outPath));
            }
                       /* FileOutputStream fos = new FileOutputStream("d:\\jiashi\\reload\\00004312bfd54291b31d77cc4b8e4c3b\\" + srcImgFile.getName()); //创建输出流对象
                        byte datas[] = new byte[1024 * 8];//创建搬运工具
                        int len = 0;//创建长度
                        while ((len = srcImgFile.read(datas)) != -1)//循环读取数据
                        {
                            fos.write(datas, 0, len);
                        }*/
            //System.out.println("输出时间"+(end3-start3)/1000.0+"s");
            return outPath;
            // 输出图片
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
            return null;
        } finally {
            if (null != g) {
                g.dispose();// 释放资源*/
            }
            if (null != bufImg) {
                bufImg.flush();
            }
            if (null != srcImg) {
                srcImg.flush();
            }
        }
    }



    public static String addWatermarkPic2(File srcImgFile, EmrPdfWaterSet pdfWaterSet, String outPath) {
        java.awt.Image srcImg = null;
        BufferedImage bufImg = null;
        Graphics2D g = null;
        try {
            srcImg = ImageIO.read(new FileInputStream(srcImgFile));
            /*if(null == srcImg){
                IIORegistry registry = IIORegistry.getDefaultInstance();
                registry.registerServiceProvider(new com.twelvemonkeys.imageio.plugins.tiff.TIFFImageWriterSpi());
                registry.registerServiceProvider(new com.twelvemonkeys.imageio.plugins.tiff.TIFFImageReaderSpi());
                srcImg = ImageIO.read(new FileInputStream(srcImgFile));
            }*/
            //System.out.println("读取图片"+(end-start)/1000.0+"s");
            int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);//获取图片的高
            // 加水印
            bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Font font = new Font("STSong-Light", Font.ITALIC, pdfWaterSet.getTextSize() * 4);//水印字体，大小
            g = bufImg.createGraphics();//得到画笔
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            //System.out.println("画图片"+(end1-start1)/1000.0+"s");
            //判断是否加水印
            Short effective = pdfWaterSet.getEffective();
            Short isImg = pdfWaterSet.getIsImg();
            if (effective == 1 || isImg == 1) {
                Color color = toColorFromString(pdfWaterSet.getTextColor());
                int degree = 0 - pdfWaterSet.getTextRotation();//设置水印文字的旋转角度
                float alpha = pdfWaterSet.getTransparent();//设置水印透明度 默认为1.0  值越小颜色越浅
                g.setColor(color); //设置水印颜色
                g.setFont(font);              //设置字体
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));//设置水印文字透明度
                g.rotate(Math.toRadians(degree), (double) bufImg.getWidth(), (double) bufImg.getHeight());//设置水印旋转
                g.drawString(pdfWaterSet.getText(), srcImg.getWidth(null) / 2 + pdfWaterSet.getTextX() , srcImg.getHeight(null) / 2 + (pdfWaterSet.getTextY() - 300));//画出水印,并设置水印位置
                //System.out.println("画文字图片"+(end2-start2)/1000.0+"s");
            }
            //ByteArrayInputStream fis = new ByteArrayInputStream(imageToByteArr);//创建输入流对象
            if (!new File(outPath).exists()) {
                ImageIO.write(bufImg, "jpg", new File(outPath));
            }
                       /* FileOutputStream fos = new FileOutputStream("d:\\jiashi\\reload\\00004312bfd54291b31d77cc4b8e4c3b\\" + srcImgFile.getName()); //创建输出流对象
                        byte datas[] = new byte[1024 * 8];//创建搬运工具
                        int len = 0;//创建长度
                        while ((len = srcImgFile.read(datas)) != -1)//循环读取数据
                        {
                            fos.write(datas, 0, len);
                        }*/
            //System.out.println("输出时间"+(end3-start3)/1000.0+"s");
            return outPath;
            // 输出图片
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
            return null;
        } finally {
            if (null != g) {
                g.dispose();// 释放资源*/
            }
            if (null != bufImg) {
                bufImg.flush();
            }
            if (null != srcImg) {
                srcImg.flush();
            }
        }
    }

    //图片合成pdf
    private static void imgToPdf(Document document, List<String> filePaths) throws Exception {
        document.open(); //打开容器
        float percent = 100;
        float w, h;
        for (String filePath : filePaths) {
            try {
                File file = new File(filePath);
                if (file.isFile()) {
                    Image img = Image.getInstance(filePath);
                    /*处理图片缩放比例*/
                    w = img.getWidth();
                    h = img.getHeight();
                    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);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        document.close(); //关闭容器
    }




    //图片合成pdf
    private static void imgToPdf2(Document document, String filePath) throws Exception {
        document.open(); //打开容器
        float percent = 100;
        float w, h;
            File file = new File(filePath);
            if (file.isFile()) {
                Image img = Image.getInstance(filePath);
                /*处理图片缩放比例*/
                w = img.getWidth();
                h = img.getHeight();
                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);
            }
        document.close(); //关闭容器
    }

    /**
     * 添加图片和文字水印
     *
     * @param
     * @param response     输出前台
     * @param upOrUnder    加水印后存放地址
     * @param transparent  加水印透明度
     * @param text         加水印的文本内容
     * @param textX        文字横坐标
     * @param textY        文字纵坐标
     * @param textColor    文字颜色
     * @param textSize     文字字号
     * @param textRotation 文字旋转角度
     * @param imgFile      加水印图片文件
     * @param imgWidth     图片宽
     * @param imgHeight    图片高
     * @param imgX         图片横坐标
     * @param imgY         图片纵坐标
     * @throws IOException
     * @throws DocumentException
     */
    public static void addWaterMark(ByteArrayOutputStream bos, HttpServletResponse response, int upOrUnder, float transparent, String text, int textX, int textY,
                                    String textColor, int textSize, int textRotation, Short effective, Short isImg,
                                    String imgFile, int imgWidth, int imgHeight, int imgX, int imgY) {
        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            reader = new PdfReader(bos.toByteArray());
            // 加完水印的文件
            if (null != response) {
                stamper = new PdfStamper(reader, response.getOutputStream());
            } else {
                stamper = new PdfStamper(reader, bos);
            }
            // 设置字体
            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 (null != isImg && isImg == 1) {
                    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                    String tomcatPath = request.getSession().getServletContext().getRealPath("/");
                    String imgStr = tomcatPath + "static\\pdfWaterSet\\upload\\" + imgFile;
                    com.lowagie.text.Image image = null;
                    if (StringUtils.isNotBlank(imgStr) && new File(imgStr).isFile()) {
                        image = com.lowagie.text.Image.getInstance(imgStr);
                        //位置
                        image.setAbsolutePosition(imgX, imgY);
                        // 设置图片的显示大小
                        image.scaleToFit(imgWidth, imgHeight);
                        content.addImage(image);
                    }
                }
                // 文字水印
                if (effective == 1 && StringUtils.isNotBlank(text)) {
                    content.beginText();
                    //16进制颜色转color
                    Color color = toColorFromString(textColor);
                    content.setColorFill(color);
                    // 设置字体及字号
                    content.setFontAndSize(font, textSize);
                    // 设置起始位置
                    content.setTextMatrix(textX, textY);
                    // 中间水印
                    content.showTextAligned(Element.ALIGN_LEFT, text, textX, textY, textRotation);
                    // 底部水印
                    content.endText();
                    //第二水印
                    content.beginText();
                    //16进制颜色转color
                    content.setColorFill(color);
                    // 设置字体及字号
                    content.setFontAndSize(font, textSize);
                    // 设置起始位置
                    content.setTextMatrix(textX, textY);
                    // 中间水印
                    content.showTextAligned(Element.ALIGN_LEFT, text, textX, textY, textRotation);
                    // 底部水印
                    content.endText();
                }
            }
        } catch (IOException | DocumentException e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        } finally {
            if (null != stamper) {
                try {
                    stamper.close();
                } catch (DocumentException | IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != reader) {
                reader.close();
            }
        }
    }
    public static void addWaterMark(ByteArrayOutputStream bos, HttpServletResponse response, int upOrUnder, float transparent, String text, int textX, int textY,
                                    String textColor, int textSize, int textRotation, Short effective, Short isImg,
                                    String imgFile, int imgWidth, int imgHeight, int imgX, int imgY,String text1) {
        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            reader = new PdfReader(bos.toByteArray());
            // 加完水印的文件
            if (null != response) {
                stamper = new PdfStamper(reader, response.getOutputStream());
            } else {
                stamper = new PdfStamper(reader, bos);
            }
            // 设置字体
            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 (null != isImg && isImg == 1) {
                    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                    String tomcatPath = request.getSession().getServletContext().getRealPath("/");
                    String imgStr = tomcatPath + "static\\pdfWaterSet\\upload\\" + imgFile;
                    com.lowagie.text.Image image = null;
                    if (StringUtils.isNotBlank(imgStr) && new File(imgStr).isFile()) {
                        image = com.lowagie.text.Image.getInstance(imgStr);
                        //位置
                        image.setAbsolutePosition(imgX, imgY);
                        // 设置图片的显示大小
                        image.scaleToFit(imgWidth, imgHeight);
                        content.addImage(image);
                    }
                }
                // 文字水印
                if (effective == 1 && StringUtils.isNotBlank(text)) {
                    content.beginText();
                    //16进制颜色转color
                    Color color = toColorFromString(textColor);
                    content.setColorFill(color);
                    // 设置字体及字号
                    content.setFontAndSize(font, textSize);
                    // 设置起始位置
                    content.setTextMatrix(textX, textY);
                    // 中间水印
                    content.showTextAligned(Element.ALIGN_LEFT, text, textX, textY, textRotation);
                    // 底部水印
                    content.endText();
                    //第二水印
                    content.beginText();
                    //16进制颜色转color
                    content.setColorFill(color);
                    // 设置字体及字号
                    content.setFontAndSize(font, textSize);
                    // 设置起始位置
                    content.setTextMatrix(textX, textY);
                    // 中间水印
                    content.showTextAligned(Element.ALIGN_LEFT, text, textX, textY, textRotation);
                    // 底部水印
                    content.endText();
                }
                if(StringUtils.isNotBlank(text1)){
                    content.beginText();
                    //16进制颜色转color
                    Color color = toColorFromString(textColor);
                    content.setColorFill(color);
                    // 设置字体及字号
                    content.setFontAndSize(font, textSize);
                    // 设置起始位置
                    content.setTextMatrix(textX, textY);
                    // 中间水印
                    content.showTextAligned(Element.ALIGN_LEFT, text1, textX, textY - 100, textRotation);
                    // 底部水印
                    content.endText();
                    //第二水印
                    content.beginText();
                    //16进制颜色转color
                    content.setColorFill(color);
                    // 设置字体及字号
                    content.setFontAndSize(font, textSize);
                    // 设置起始位置
                    content.setTextMatrix(textX, textY);
                    // 中间水印
                    content.showTextAligned(Element.ALIGN_LEFT, text, textX, textY, textRotation);
                    // 底部水印
                    content.endText();
                }
            }
        } catch (IOException | DocumentException e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        } finally {
            if (null != stamper) {
                try {
                    stamper.close();
                } catch (DocumentException | IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != reader) {
                reader.close();
            }
        }
    }

    private static void addWaterMarkFont(ByteArrayOutputStream bos, int upOrUnder, float transparent, String text, int textX, int textY,
                                         String textColor, int textSize, int textRotation, Short effective, Short isImg,
                                         String imgFile, int imgWidth, int imgHeight, int imgX, int imgY, String fileOutPath) {
        //ByteArrayInputStream fileToUpload = new ByteArrayInputStream(bos.toByteArray());
        // 待加水印的文件
        //String fileStr = "e:\\11111.pdf";
        PdfReader reader = null;
        OutputStream out = null;
        PdfStamper stamper = null;
        try {
            reader = new PdfReader(bos.toByteArray());
            //输出到本地
            out = new FileOutputStream(fileOutPath);
            // 加完水印的文件
            stamper = new PdfStamper(reader, out);
            //设置不允许打印
/*
            stamper.setEncryption(null, null,   ~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING ), PdfWriter.STANDARD_ENCRYPTION_128);
*/
            // 设置字体
            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 (null != isImg && isImg == 1) {
                    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                    String tomcatPath = request.getSession().getServletContext().getRealPath("/");
                    String imgStr = tomcatPath + "static\\pdfWaterSet\\upload\\" + imgFile;
                    com.lowagie.text.Image image = null;
                    if (StringUtils.isNotBlank(imgStr) && new File(imgStr).isFile()) {
                        image = com.lowagie.text.Image.getInstance(imgStr);
                        //位置
                        image.setAbsolutePosition(imgX, imgY);
                        // 设置图片的显示大小
                        image.scaleToFit(imgWidth, imgHeight);
                        content.addImage(image);
                    }
                }
                // 文字水印
                if (effective == 1 && StringUtils.isNotBlank(text)) {
                    content.beginText();
                    //16进制颜色转color
                    Color color = toColorFromString(textColor);
                    content.setColorFill(color);
                    // 设置字体及字号
                    content.setFontAndSize(font, textSize);
                    // 设置起始位置
                    content.setTextMatrix(textX, textY);
                    // 中间水印
                    content.showTextAligned(Element.ALIGN_LEFT, text, textX, textY, textRotation);
                    content.endText();
                }
            }
        } catch (IOException | DocumentException e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        } finally {
            if (null != stamper) {
                try {
                    stamper.close();
                } catch (DocumentException | IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != reader) {
                reader.close();
            }
        }
    }

    /**
     * 字符串转换成Color对象
     *
     * @param colorStr 16进制颜色字符串
     * @return Color对象
     */
    private static Color toColorFromString(String colorStr) {
        int r = Integer.valueOf(colorStr.substring(1, 3), 16);
        int g = Integer.valueOf(colorStr.substring(3, 5), 16);
        int b = Integer.valueOf(colorStr.substring(5, 7), 16);
        //java.awt.Color[r=0,g=0,b=255]
        return new Color(r, g, b);
    }

    /**
     * 将 tiff 转换 jpg 格式
     * @param filePath
     * @return
     */

/*
    public static String tiffTuanJPG(String filePath){
        String format = filePath.substring(filePath.lastIndexOf(".")+1);
        String turnJpgFile = filePath.replace("tiff", "jpg");
        if(format.equals("tiff")){
            File fileTiff = new File(turnJpgFile);
            if(fileTiff.exists()){
                System.out.println("该tiff文件已经转换为 JPG 文件："+turnJpgFile);
                return turnJpgFile;
            }
            RenderedOp rd = JAI.create("fileload", filePath);//读取iff文件
            OutputStream ops = null;
            try {
                ops = new FileOutputStream(turnJpgFile);
                //文件存储输出流
                JPEGEncodeParam param = new JPEGEncodeParam();
                ImageEncoder image = ImageCodec.createImageEncoder("JPEG", ops, param); //指定输出格式
                image.encode(rd );
                //解析输出流进行输出
                ops.close();
                System.out.println("tiff转换jpg成功:"+filePath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return turnJpgFile;
    }
*/
}
