html转pdf


1.记录一下


public class Html2Pdf {

    public static void main(String[] args) throws IOException {
        //Html2Pdf html2Pdf = new Html2Pdf();
        //html2Pdf.html2pdf("file:///E:/%E9%A1%B9%E7%9B%AE/%E8%A5%BF%E5%AE%89%E5%B8%82%E7%A7%91%E6%8A%80%E5%B1%80/SVN/%E6%96%87%E6%A1%A3/20%E9%A1%B9%E7%9B%AE%E5%BC%80%E5%8F%91/UI%E4%B8%8E%E5%89%8D%E7%AB%AF%E9%A1%B5%E9%9D%A2/v1.0/%E5%89%8D%E7%AB%AF%E7%95%8C%E9%9D%A2%E5%BC%80%E5%8F%91/web/westcredit/pdf2.html");
//        String path = Html2Pdf.class.getClass().getResource("/").getPath();
//        System.out.println(path);
//
//        // 第一种:获取类加载的根路径   D:\git\daotie\daotie\target\classes
//        File f = new File(Html2Pdf.class.getClass().getResource("/").getPath());
//        System.out.println(f);
//
//        // 获取当前类的所在工程路径; 如果不加“/”  获取当前类的加载目录  D:\git\daotie\daotie\target\classes\my
        File f2 = new File(Html2Pdf.class.getClass().getResource("").getPath());
        System.out.println(f2);
//
//        // 第二种:获取项目路径    D:\git\daotie\daotie
//        File directory = new File("");// 参数为空
//        String courseFile = directory.getCanonicalPath();
//        System.out.println(courseFile);
//
//
//        // 第三种:  file:/D:/git/daotie/daotie/target/classes/
        URL xmlpath = Html2Pdf.class.getClass().getClassLoader().getResource("/");
        System.out.println(xmlpath);
//
//
//        // 第四种: D:\git\daotie\daotie
//        System.out.println(System.getProperty("user.dir"));
//        /*
//         * 结果: C:\Documents and Settings\Administrator\workspace\projectName
//         * 获取当前工程路径
//         */
//
//        // 第五种:  获取所有的类路径 包括jar包的路径
//        System.out.println(System.getProperty("java.class.path"));
    }

    private final static Logger LOGGER = LoggerFactory.getLogger(Html2Pdf.class);
    private Random random = new Random();
//    public byte[] html2pdf(String srcUrl) {
//        String tmp = System.getProperty("java.io.tmpdir");
//        String filename = System.currentTimeMillis() + random.nextInt(1000) + ".pdf";
//        //return html2pdf(srcUrl, tmp + "/" + filename);
//        return html2pdf(srcUrl, tmp + filename);
//    }
    public byte[] html2pdf(String src, String dest) {
        System.out.println("******************************************************************");
        System.out.println(System.getProperty("user.dir").replace("\\", "/"));
        System.out.println("******************************************************************");
        String space = " ";
        //String wkhtmltopdf = findExecutable();
        String wkhtmltopdf = StpsmpGlobal.getConfig("wkhtmltopdf.home") + "/bin/wkhtmltopdf.exe";
        if (StringUtils.isEmpty(wkhtmltopdf)) {
            LOGGER.error("no wkhtmltopdf found!");
            //throw new RuntimeException("html转换pdf出错了");

        }
        File file = new File(dest);
        File parent = file.getParentFile();
        if (!parent.exists()) {
            boolean dirsCreation = parent.mkdirs();
            LOGGER.info("create dir for new file,{}", dirsCreation);
        }
        StringBuilder cmd = new StringBuilder();
        cmd.append(wkhtmltopdf).append(space)
                .append(src).append(space)
                .append("--footer-right").append(space).append("页码:[page]").append(space)
                .append("--footer-font-size").append(space).append("5").append(space)
                .append("--disable-smart-shrinking").append(space)
                .append("--load-media-error-handling")
                .append(space).append("ignore").append(space)
                .append("--load-error-handling").append(space).append("ignore").append(space)
                .append("--footer-left").append(space).append("电子档打印时间:[date]").append(space)
                .append(dest);
        InputStream is = null;
        try {
            String finalCmd = cmd.toString();
            LOGGER.info("final cmd:{}", finalCmd);
            Process proc = Runtime.getRuntime().exec(finalCmd);
            new Thread(new ProcessStreamHandler(proc.getInputStream())).start();
            new Thread(new ProcessStreamHandler(proc.getErrorStream())).start();
            proc.waitFor();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            is = new FileInputStream(file);
            byte[] buf = new byte[1024];
            while (is.read(buf, 0, buf.length) != -1) {
                baos.write(buf, 0, buf.length);
            }
            return baos.toByteArray();
        } catch (Exception e) {
            LOGGER.error("html转换pdf出错", e);
            throw new RuntimeException("html转换pdf出错了");
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * Attempts to find the `wkhtmltopdf` executable in the system path.
     *
     * @return the wkhtmltopdf command according to the OS
     */
    public String findExecutable() {
        Process p;
        try {
            String osname = System.getProperty("os.name").toLowerCase();
            String cmd = osname.contains("windows") ? "where wkhtmltopdf" : "which wkhtmltopdf";
            p = Runtime.getRuntime().exec(cmd);
            new Thread(new ProcessStreamHandler(p.getErrorStream())).start();
            p.waitFor();
            return IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
        } catch (Exception e) {
            LOGGER.error("no wkhtmltopdf found!", e);
        }
        return "";
    }

    private static class ProcessStreamHandler implements Runnable {
        private InputStream is;
        public ProcessStreamHandler(InputStream is) {
            this.is = is;
        }
        @Override
        public void run() {
            BufferedReader reader = null;
            try {
                InputStreamReader isr = new InputStreamReader(is, "GBK");
                reader = new BufferedReader(isr);
                String line;
                while ((line = reader.readLine()) != null) {
                    if (LOGGER.isDebugEnabled())
                        System.out.println(line); //输出内容
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值