java通过html转pdf

HTML转PDF工具(wkhtmltopdf)介绍,支持widows和linux
wkhtmltopdf下载地址:链接:http://pan.baidu.com/s/1jIkk9Wa 密码:ljn6

cmd用法:
这里写图片描述

java用法:

package com.yanhui.test;

import java.io.*;;

public class HtmlToPdf {


        private static final String TOPDFTOOL = "D://Program Files//wkhtmltopdf//bin//wkhtmltopdf.exe";

        /**
         * html转pdf
         * @param srcPath html路径,可以是硬盘上的路径,也可以是网络路径
         * @param destPath pdf保存路径
         * @return 转换成功返回true
         */
        public static boolean convert(String srcPath, String destPath) {

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

            //c:\wkhtmltopdf.exe http://www.csdn.net c:\csdn.pdf"
            StringBuilder cmd = new StringBuilder();
            cmd.append(TOPDFTOOL);
            cmd.append(" ");
            cmd.append(srcPath);
            cmd.append(" ");
            cmd.append(destPath);

            boolean result = true;
            try {
                Process proc = Runtime.getRuntime().exec(cmd.toString());
                HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
                HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(
                        proc.getInputStream());
                error.start();
                output.start();
                proc.waitFor();
                System.out.println("HTML2PDF成功,参数---html路径:{},pdf保存路径 :{}"+new Object[] {srcPath, destPath });
            } catch (Exception e) {
                System.out.println(("HTML2PDF失败,srcPath地址:{},错误信息:{}"));
                result = false;
            }
            return result;
        }

        public static void main(String[] args) {
            String htmlPath = "http://www.baidu.com";
            String pdfPath = "D://testpdf2.pdf";
            HtmlToPdf.convert(htmlPath, pdfPath );
        }


}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HtmlToPdfInterceptor extends Thread {


        private InputStream is;

        public HtmlToPdfInterceptor(InputStream is) {
            this.is = is;
        }

        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

全CSDN的丰(好)色(se)博客,这里有书本看不到的Java技术,电影院禁播的电影,欢迎关注QQ群494808400

展开阅读全文

没有更多推荐了,返回首页