package com.ruoyi.common.utils;


import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import java.io.*;

public class PdfUtil {


    public static boolean getLicense(String licensePath) {
        boolean result = false;
        InputStream is = null;
        try {
            is = new FileInputStream(licensePath);
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String osName = System.getProperty("os.name");
        System.out.println(osName);
    }

    public static boolean doc2pdf(String inPath, String outPath, String licensePath) {
        if (!getLicense(licensePath)) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            String osName = System.getProperty("os.name");
            if (osName != null && osName.trim().toLowerCase().contains("linux")) {
                FontSettings.setFontsFolder("/usr/share/fonts/chinese" + File.separator, true);//此处处理乱码和小方块
            }
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功，共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
}
