package com.sunxung.factoring.component.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.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;

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