package com.yizhi.application.Certificate.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public class HtmltopdfAndImage {

    private static final Logger LOG = LoggerFactory.getLogger(HtmltopdfAndImage.class);
 
 //   private static final String TOPDFTOOL = "D:\\wkhtmltopdf\\wkhtmltox\\bin\\wkhtmltopdf.exe";
//    private static final String TOIMGTOOL = "D:\\development\\wkhtmltopdf\\bin\\wkhtmltoimage.exe";
    private static final String TOPDFTOOL = "wkhtmltopdf";
    private static final String TOIMGTOOL = "wkhtmltoimage";

//

    /**
     * html转pdf或者Img
     *
     * @param srcPath  html路径，可以是硬盘上的路径，也可以是网络路径
     * @param destPath pdf或者Image保存路径
     * @param outType  需要生成的文件类型：1.pdf 2.jpg
     * @return 转换成功返回true
     */
    public static boolean convert(String srcPath, String destPath, int outType,int height,int width) {

        File file = new File(destPath);
        File parent = file.getParentFile();
        // 如果pdf保存路径不存在，则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }

        StringBuilder cmd = new StringBuilder();
        
        if (outType == 1) {
            cmd.append(TOPDFTOOL);
        } else if (outType == 2) {
            cmd.append(TOIMGTOOL);
        }
        cmd.append(" ");
//        cmd.append("--page-size A2");// 参数
        if(width>height ){
            cmd.append("--page-width ").append(297).append("mm");
            cmd.append(" ");
            cmd.append("--page-height ").append(210).append("mm");
            cmd.append(" ");
        }else {
            cmd.append("--page-size A4");// 参数
            cmd.append(" ");
        }
        cmd.append(srcPath);
        cmd.append(" ");
        cmd.append(destPath);
        System.out.println("cmd:"+cmd);

        boolean result = true;
        try {
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            HtmlToPdfInter error = new HtmlToPdfInter(
                    proc.getErrorStream());
            HtmlToPdfInter output = new HtmlToPdfInter(
                    proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
            LOG.info("转换成功，参数---html路径：{},pdf保存路径 ：{}", new Object[]{srcPath, destPath});
        } catch (Exception e) {
            LOG.error("转换失败，srcPath地址：{},错误信息：{}", new Object[]{srcPath, e.getMessage()});
            result = false;
        }
        return result;
    }
}