package com.inkasso.factoring.common.util;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import java.io.*;

public class PdfUtil {

    /**
     * word转pdf
     * @param wordFilePath word文件路径
     * @param pdfFilePath  pdf文件路径
     * @return 成功或失败
     * 注意 ： 给方法在本地测试成功  但是打包后就无法生效  慎用
     */
    public static boolean docxToPdf(String wordFilePath, String pdfFilePath) {
        boolean result = false;

        File inputFile = new File(wordFilePath);
        File outputFile = new File(pdfFilePath);
        try {
            InputStream inputStream = new FileInputStream(inputFile);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(inputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();

            outputStream.close();
            result = true;
        } catch (Exception e) {

            e.printStackTrace();
        }

        return result;
    }

    /**
     * 图片转PDF  jpg  png bmp jpeg格式测试过  其他格式暂未测试
     * @param source 源文件路径
     * @param target 生成的PDF文件路径
     */
    public static void convert(String source, String target) {
        Document document = new Document();
        //设置文档页边距
        document.setMargins(0,0,0,0);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(target);
            PdfWriter.getInstance(document, fos);
            //打开文档
            document.open();
            //获取图片的宽高
            Image image = Image.getInstance(source);
            float imageHeight=image.getScaledHeight();
            float imageWidth=image.getScaledWidth();
            //设置页面宽高与图片一致
            Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
            document.setPageSize(rectangle);
            //图片居中
            image.setAlignment(Image.ALIGN_CENTER);
            //新建一页添加图片
            document.newPage();
            document.add(image);
        } catch (Exception ioe) {
            System.out.println(ioe.getMessage());
        } finally {
            //关闭文档
            document.close();
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * pdf文件添加文字水印
     * @param srcPath 输入的文件路径
     * @param destPath 输出的文件路径
     * @param word 水印文字
     * @throws Exception
     */
    public static void addPDFWaterMark(String srcPath, String destPath, String word)
        throws Exception {

        PdfReader reader = new PdfReader(srcPath);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPath));

        //使用系统字体
        String prefixFont = null;
        String os = System.getProperties().getProperty("os.name");
        if (os.startsWith("win") || os.startsWith("Win")) {
            prefixFont = "C:\\Windows\\Fonts\\SIMSUN.TTC,1";
        } else {
            prefixFont = "/usr/share/fonts/chinese/TrueType/uming.ttf";
        }

        //创建字体，第一个参数是字体路径
        BaseFont base = BaseFont.createFont(prefixFont, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        //BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

        PdfGState gs = new PdfGState();
        gs.setFillOpacity(0.6f);//图片水印透明度
        //gs.setStrokeOpacity(0.4f);//设置笔触字体不透明度
        PdfContentByte content = null;

        int total = reader.getNumberOfPages();//pdf文件页数
        for (int i=0; i<total; i++) {
            float x = reader.getPageSize(i+1).getWidth();//页宽度
            float y = reader.getPageSize(i+1).getHeight();//页高度
            content = stamper.getOverContent(i+1);
            content.setGState(gs);
            content.beginText();//开始写入
            content.setFontAndSize(base, 10);//字体大小
            content.setRGBColorFill(0,0,0);
            //showTextAligned 方法的参数（文字对齐方式，位置内容，输出水印X轴位置，Y轴位置，旋转角度）
            content.showTextAligned(Element.ALIGN_CENTER, word, x/3+30, y/20, 0);
            content.endText();//结束写入
        }
        //关闭流
        stamper.close();
        reader.close();
    }

}