最近,项目需要将HTML页面转换为PDF文件,所以就研究了下HTML转PDF的解决方案,发现网上比较流行的解决方案有3种:

(1)iText

(2)Flying Saucer

(3)wkhtmltopdf

还有一些收费的,我就没测试过了,前两种对HTML的要求过于严格,而且即使你写标准的HTML(当然这都是理想情况下),他也未必可以完美解析,所以我就选择了(3),wkhtmltopdf基于WebKit渲染引擎将HTML内容转换为HTML页面,之后再转换成PDF,所以其转换后的PDF文件的显示效果可以和HTML页面基本保持一致,是一个相当完美的解决方案,美中不足的是他需要你安装插件,并不能像前两种解决方案那样以jar包的形式嵌入到项目中。

因为在使用的过程中,也发现了一些问题,所以就把自己的解决方案写出来,供需要的朋友参考。

CustomWKHtmlToPdfUtil.java是自定义的一个操作wkhtmltopdf的工具类:

  1. package us.kagome.wkhtmltopdf;
  2.  
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.OutputStream;
  6. import java.util.UUID;
  7.  
  8. /**
  9. * wkhtmltopdf工具类
  10. *
  11. * 约定:
  12. * 1. 插件安装位置,在Windows系统中将插件安装在D盘根目录下(D:/), 在Linux系统中将插件安装在opt目录下(/opt)
  13. *
  14. * 注意:
  15. * 1. wkhtmltopdf的Linux版本中,解压后,默认的文件名为"wkhtmltox",为了统一起见,一律将解压后的文件名,重命名为"wkhtmltopdf"(命令:mv wkhtmltox wkhtmltopdf)
  16. *
  17. * Created by kagome on 2016/7/26.
  18. */
  19. public class CustomWKHtmlToPdfUtil {
  20. // 临时目录的路径
  21. public static final String TEMP_DIR_PATH = CustomWKHtmlToPdfUtil.class.getResource("/").getPath().substring(1) + "temp/";
  22.  
  23. static {
  24. // 生成临时目录
  25. new File(TEMP_DIR_PATH).mkdirs();
  26. }
  27.  
  28. public static void main(String[] args) throws Exception {
  29. String htmlStr = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\"></meta><title>HTML转PDF</title></head><body><h1>Hello 世界!</h1></body></html>";
  30.  
  31. htmlToPdf(strToHtmlFile(htmlStr), TEMP_DIR_PATH + UUID.randomUUID().toString() + ".pdf");
  32. }
  33.  
  34. /**
  35. * 将HTML文件内容输出为PDF文件
  36. *
  37. * @param htmlFilePath HTML文件路径
  38. * @param pdfFilePath PDF文件路径
  39. */
  40. public static void htmlToPdf(String htmlFilePath, String pdfFilePath) {
  41. try {
  42. Process process = Runtime.getRuntime().exec(getCommand(htmlFilePath, pdfFilePath));
  43. new Thread(new ClearBufferThread(process.getInputStream())).start();
  44. new Thread(new ClearBufferThread(process.getErrorStream())).start();
  45. process.waitFor();
  46. } catch (Exception e) {
  47. throw new RuntimeException(e);
  48. }
  49. }
  50.  
  51. /**
  52. * 将HTML字符串转换为HTML文件
  53. *
  54. * @param htmlStr HTML字符串
  55. * @return HTML文件的绝对路径
  56. */
  57. public static String strToHtmlFile(String htmlStr) {
  58. OutputStream outputStream = null;
  59. try {
  60. String htmlFilePath = TEMP_DIR_PATH + UUID.randomUUID().toString() + ".html";
  61. outputStream = new FileOutputStream(htmlFilePath);
  62. outputStream.write(htmlStr.getBytes("UTF-8"));
  63. return htmlFilePath;
  64. } catch (Exception e) {
  65. throw new RuntimeException(e);
  66. } finally {
  67. try {
  68. if (outputStream != null) {
  69. outputStream.close();
  70. outputStream = null;
  71. }
  72. } catch (Exception e) {
  73. throw new RuntimeException(e);
  74. }
  75. }
  76. }
  77.  
  78. /**
  79. * 获得HTML转PDF的命令语句
  80. *
  81. * @param htmlFilePath HTML文件路径
  82. * @param pdfFilePath PDF文件路径
  83. * @return HTML转PDF的命令语句
  84. */
  85. private static String getCommand(String htmlFilePath, String pdfFilePath) {
  86. String osName = System.getProperty("os.name");
  87. // Windows
  88. if (osName.startsWith("Windows")) {
  89. return String.format("D:/wkhtmltopdf/bin/wkhtmltopdf.exe %s %s", htmlFilePath, pdfFilePath);
  90. }
  91. // Linux
  92. else {
  93. return String.format("/opt/wkhtmltopdf/bin/wkhtmltopdf %s %s", htmlFilePath, pdfFilePath);
  94. }
  95. }
  96.  
  97. }

ClearBufferThread.java用于清空Process的输入流的缓存的线程类:

  1. package us.kagome.wkhtmltopdf;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6.  
  7. /**
  8. * 清理输入流缓存的线程
  9. * Created by kagome on 2016/8/9.
  10. */
  11. public class ClearBufferThread implements Runnable {
  12. private InputStream inputStream;
  13.  
  14. public ClearBufferThread(InputStream inputStream){
  15. this.inputStream = inputStream;
  16. }
  17.  
  18. public void run() {
  19. try{
  20. BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
  21. while(br.readLine() != null);
  22. } catch(Exception e){
  23. throw new RuntimeException(e);
  24. }
  25. }
  26. }

以上是解决方案的完整代码,接下来说下自己遇到的问题吧!

(1)在jdk1.6环境下,下面代码会造成阻塞:

  1. process.waitFor();

导致程序不能正常执行,jdk1.7就没有这个问题了,去网上找了好久,发现是Process的输入流和错误流缓存不足导致的,所以就增加了ClearBufferThread类用于清空输入流缓存。

使用wkhtmltopdf实现HTML转PDF的解决方案的更多相关文章

  1. Java操作wkhtmltopdf实现Html转PDF

    做java开发的都知道,java生成pdf大部分都是用itext,itext的确是java开源组件的第一选择.不过itext也有局限,就是要自己写模版,系统中的表单数量有好几百个,为每个表单做一个导出 ...

  2. wkhtmltopdf 将网页转换为PDF和图片

    wkhtmltopdf 是一个shell工具,它使用了WebKit渲染引擎和Qt,将网页html转换为pdf的强大工具,转换后的pdf也可以通过pdf工具进行复制.备注.修改 官网下载地址:http: ...

  3. C# wkhtmltopdf 将html转pdf(详解)

    https://www.cnblogs.com/louby/p/905198.html转自,看文章只放了代码看起来云里雾里的,在此做些解析 使用说明: 1.首先呢,得安装下软件,地址下面有链接,文件里 ...

  4. C# wkhtmltopdf 将html转pdf

    一.转换程序代码如下: public string HtmlToPdf(string url) { bool success = true; // string dwbh = url.Split('? ...

  5. wkhtmltopdf导出html到pdf

    1.使用背景     最近公司需要把html页面的内容生成pdf并下载,试过很多方法都没有满意的效果,后来找到wkhtmltopdf这款软件,终于解决了这个问题. wkhtmltopdf是exe文件, ...

  6. wkhtmltopdf cpdf HTML转pdf 及pdf合并

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

  7. Web方式预览Office/Word/Excel/pdf文件解决方案

    最近在做项目时需要在Web端预览一些Office文件,经过在万能的互联网上一番搜索确定并解决了. 虽然其中碰到的一些问题已经通过搜索和自己研究解决了,但是觉得有必要将整个过程记录下来,以方便自己以后查 ...

  8. wkhtmltopdf 将网页生成pdf文件

    先安装依赖 yum install fontconfig libXrender libXext xorg-x11-fonts-Type1 xorg-x11-fonts-75dpi freetype l ...

  9. 使用com.aspose.words将word模板转为PDF乱码解决方案(window下正常)

    最近在做电子签名过程中,需要将合成的电子签名的word文件(正常)转换为pdf文件时,在开发平台window下转换没有问题,中文也不会出现乱码.但是将项目部署到正式服务器(Linux)上,转换出来的p ...

随机推荐

  1. java基本类型转换规则

    自动类型转换,也称隐式类型转换,是指不需要书写代码,由系统自动完成的类型转换.由于实际开发中这样的类型转换很多,所以Java语言在设计时,没有为该操作设计语法,而是由JVM自动完成. 具体规则为: b ...

  2. CF Gym 100685E Epic Fail of a Genie

    传送门 E. Epic Fail of a Genie time limit per test 0.5 seconds memory limit per test 64 megabytes input ...

  3. Bootstrap Modals(模态框)

    http://www.runoob.com/bootstrap/bootstrap-v2-modal-plugin.html 描述 Bootstrap Modals(模态框)是使用定制的 Jquery ...

  4. ci控制器写规范

    不需要后缀名 文件名全部小写 所有控制器需要直接或者间接继承CI_Controller 以下划线开头的方法为私有方法,不能被请求 protected private的方法不能被浏览器请求 ci方法名不 ...

  5. vc++ 6.0下Glut的配置 及 Glut 框架介绍

    2014-04-08  16:18:30 一.配置Glut 学习来源: http://blog.sina.com.cn/s/blog_5f0cf7bd0100c9oa.html 亲测可行. Glut的 ...

  6. hdu 2045 不容易系列之(3)—— LELE的RPG难题

    解题思路: f(n)=1,2,.....n-2,n-1,n 前n-2个已经涂好,那么n-1有两种可能 1.n-1与n-2和1 的颜色都不同 1 粉,   n-2 红,   n-1 绿.  那么n的颜色 ...

  7. rsyslog 与 logrotate 服务

    rsyslog与logrotate服务 rsyslog 负责写入日志, logrotate负责备份和删除旧日志, 以及更新日志文件. 一.rsyslog rsyslog 是一个 syslogd 的多线 ...

  8. SQLServer 删除所有表的外键约束

    )) begin exec(@c1) fetch next from c1 into @c1 endclose c1deallocate c1

  9. UrlConnection连接和Socket连接的区别

    关于UrlConnection连接和Socket连接的区别,只知道其中的原理如下: 抽象一点的说,Socket只是一个供上层调用的抽象接口,隐躲了传输层协议的细节. urlconnection 基于H ...

  10. 操作sqlserver数据库常用的三个方法

    1. ADO.NET -> 连接字符串,常用的两种方式: server=计算机名或ip\实例名;database=数据库名;uid=sa;pwd=密码; server=计算机名或ip\实例名;d ...