HTML转PDF工具(wkhtmltopdf)介绍,支持widows和linux

来源:互联网 发布:阿里云网站建设方案 编辑:程序博客网 时间:2024/06/16 11:49

wkhtmltopdf是一个使用webkit网页渲染引擎开发的用来将 html转成 pdf的工具,可以跟多种脚本语言进行集成来转换文档。

官网地址 http://wkhtmltopdf.org/

github地址 https://github.com/wkhtmltopdf/wkhtmltopdf


首先下载文件:html转为pdf文件(wkhtmltox)(包括windows下exe安装文件和Linux下可执行文件),官方下载地址

一、windows下操作步骤

  1. 安装:wkhtmltox-0.12.3.2_msvc2013-win64.exe,cmd命令进入安装目录

  2. 运行:wkhtmltopdf.exe [参数,可选,可多个;wkhtmltopdf中文参数详解] <需要转的html路径,必填,可多个> <转成功后的pdf文件存放地址,必填>

    a.例子: wkhtmltopdf.exe –page-size A4 www.baidu.com pdf.pdf

二、Linux下操作步骤

  1. 解压:命令:tar -xvf wkhtmltox-0.12.3_linux-generic-amd64.tar.xz

  2. 解决中文不显示或乱码问题:需要字体文件cjkuni-uming、smc、stix放入/usr/share/fonts目录下

  3. 运行:进入wkhtmltox/bin目录 ./wkhtmltopdf [参数,可选,可多个;wkhtmltopdf中文参数详解] <需要转的html路径,必填,可多个> <转成功后的pdf文件存放地址,必填>

    a.例子: ./wkhtmltopdf –page-size A4 www.baidu.com pdf.pdf

三、通过Java调用wkhtmltox的可执行文件实现批量html转pdf

public class HtmlToPdf {    private static final Logger LOG = LoggerFactory.getLogger(HtmlToPdf.class);    private static final String TOPDFTOOL = "/root/wkhtmltox/bin/wkhtmltopdf";    /**     * 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();        }        StringBuilder cmd = new StringBuilder();        cmd.append(TOPDFTOOL);        cmd.append(" ");        cmd.append("--page-size A2");// 参数        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();            LOG.info("HTML2PDF成功,参数---html路径:{},pdf保存路径 :{}", new Object[] {srcPath, destPath });        } catch (Exception e) {            LOG.error("HTML2PDF失败,srcPath地址:{},错误信息:{}", new Object[]{srcPath, e.getMessage()});            result = false;        }        return result;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
/** * 当java调用wkhtmltopdf时,用于获取wkhtmltopdf返回的内容 */public class HtmlToPdfInterceptor extends Thread {    private static final Logger LOG = LoggerFactory            .getLogger(HtmlToPdfInterceptor.class);    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) {            LOG.error(e.getMessage());            e.printStackTrace();        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
/** * 测试 */public class Test {    public static void main(String[] args) {        String htmlPath = "www.baidu.com";        String pdfPath = "/root/pdfFile/testpdf.pdf";        HtmlToPdf.convert(htmlPath, pdfPath );    }}




另一篇不错的文章:

项目上的客户提出一个需求,把政务流程中的表单数据导出成pdf或者图片格式,用来作电子档案材料。表单基于公司的电子政务构建平台实现,在数据库保存的都是html格式,因此打算直接把表单html转成pdf或者图片。由于表单是已经写好了html页面,那我要做的就是能完美解析html+css的pdf生成工具。在百度上搜索html转pdf的结果,大部分都是用itext,itext的确是Java开源组件的第一选择。不过itext也有局限,就是要自己写模版,系统中的表单数量有好几百个,为每个表单做一个导出模版不现实。 

最后,wkhtmltopdf进入了我的选择范围。wkhtmltopdf是一个使用webkit网页渲染引擎开发的用来将 html转成 pdf的工具,可以跟多种脚本语言进行集成来转换文档。

官网地址 http://wkhtmltopdf.org/

github地址 https://github.com/wkhtmltopdf/wkhtmltopdf

wkhtmltopdf把html转成pdf很简单,只要在windows命令行中输入

c:\wkhtmltopdf.exe http://www.csdn.NET c:\csdn.pdf

就可以把csdn网页转成pdf,并保存到C盘根目录。

在java中调用wkhtmltopdf的命令Runtime.getRuntime().exec("c:\wkhtmltopdf.exe http://www.csdn.Net c:\csdn.pdf")就可以实现转换。

下面把命令封装成java工具类,方便调用。

[java] view plain copy
  1. import java.io.File;  
  2.   
  3. public class HtmlToPdf {  
  4.     //wkhtmltopdf在系统中的路径  
  5.     private static final String toPdfTool = "c:\\wkhtmltopdf.exe";  
  6.       
  7.     /** 
  8.      * html转pdf 
  9.      * @param srcPath html路径,可以是硬盘上的路径,也可以是网络路径 
  10.      * @param destPath pdf保存路径 
  11.      * @return 转换成功返回true 
  12.      */  
  13.     public static boolean convert(String srcPath, String destPath){  
  14.         File file = new File(destPath);  
  15.         File parent = file.getParentFile();  
  16.         //如果pdf保存路径不存在,则创建路径  
  17.         if(!parent.exists()){  
  18.             parent.mkdirs();  
  19.         }  
  20.           
  21.         StringBuilder cmd = new StringBuilder();  
  22.         cmd.append(toPdfTool);  
  23.         cmd.append(" ");  
  24.         cmd.append(srcPath);  
  25.         cmd.append(" ");  
  26.         cmd.append(destPath);  
  27.           
  28.         boolean result = true;  
  29.         try{  
  30.             Process proc = Runtime.getRuntime().exec(cmd.toString());  
  31.             HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());  
  32.             HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());  
  33.             error.start();  
  34.             output.start();  
  35.             proc.waitFor();  
  36.         }catch(Exception e){  
  37.             result = false;  
  38.             e.printStackTrace();  
  39.         }  
  40.           
  41.         return result;  
  42.     }  
  43. }  

接收Process的输入和错误信息时,需要创建另外的线程,否则当前线程会一直等待(在Tomcat中有这种现象)。

[java] view plain copy
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.InputStreamReader;  
  5.   
  6. /** 
  7.  * 当java调用wkhtmltopdf时,用于获取wkhtmltopdf返回的内容 
  8.  */  
  9. public class HtmlToPdfInterceptor extends Thread {  
  10.     private InputStream is;  
  11.       
  12.     public HtmlToPdfInterceptor(InputStream is){  
  13.         this.is = is;  
  14.     }  
  15.       
  16.     public void run(){  
  17.         try{  
  18.             InputStreamReader isr = new InputStreamReader(is, "utf-8");  
  19.             BufferedReader br = new BufferedReader(isr);  
  20.             String line = null;  
  21.             while ((line = br.readLine()) != null) {  
  22.                 System.outlprintln(line.toString()); //输出内容  
  23.             }  
  24.         }catch (IOException e){  
  25.             e.printStackTrace();  
  26.         }  
  27.     }  
  28. }  

在Servlet中调用

[java] view plain copy
  1. /** 
  2.  * Html转PDF 
  3.  */  
  4. @WebServlet("/htmltopdf/servlet")  
  5. public class HtmlToPdfServlet extends HttpServlet {  
  6.     private static final long serialVersionUID = 1L;  
  7.       
  8.     /** 
  9.      * Servlet接收参数path,获取html的url 
  10.      */  
  11.     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  12.         String path = request.getParameter("path");  
  13.         if(path == null || path.equals("")){  
  14.             return;  
  15.         }  
  16.           
  17.         //获取pdf的临时保存路径  
  18.         //tmp为网站下的目录  
  19.         //把生成的pdf放到网站下以便下载  
  20.         String pdfPath = request.getSession().getServletContext().getRealPath("/tmp");  
  21.         String pdfName = UUID.randomUUID().toString() + ".pdf";  
  22.           
  23.         if(HtmlToPdf.convert(path, pdfPath + "/" + pdfName)){  
  24.             response.sendRedirect(request.getContextPath() + "/tmp/" + pdfName);  
  25.         }  
  26.     }  
  27. }  

在浏览器中输入http://<网站路径>/htmltopdf/servlet?path=http://blog.csdn.net


0 0
原创粉丝点击