wkhtmltopdf-实现Html转pdf

一、什么是wkhtmltopdf?

wkhtmltopdf和wkhtmltoimage是开源(LGPLv3)命令行工具,使用Qt WebKit渲染引擎将HTML呈现为PDF和各种图像格式。

一、如何安装和使用wkhtmltopdf?

(一)下载

        官网下载地址:https://wkhtmltopdf.org/downloads.html  这里可以支持多种系统使用此工具

(二)window安装和使用示例

        1、window安装  (示例使用系统版本:window10)

        这里下载最新版本 wkhtmltox-0.12.5-1.msvc2015-win64.exe 安装

        2、使用 进入到文件安装bin目录下,打开cmd命令行窗口,输入以下内容

        3、查看文件,这里虽然将百度首页转换成功,但并没有完全展示百度首页,具体情况还需探索

        4、在 java 中使用代码实现转换

public class HtmlToPDF {

    //wkhtmltopdf安装路径
    public static final String toPdfTool = "D:/wkhtmltopdf/bin/wkhtmltopdf.exe";


    public static void convert(String pageSize,String srcPath, String destPath){
        File file = new File(destPath);
        File parent = file.getParentFile();
        if (!parent.exists()){
            parent.mkdirs();
        }
        StringBuilder cmd = new StringBuilder();
        cmd.append(toPdfTool).append(" ");
        cmd.append("--page-size ");
        cmd.append(pageSize).append(" ");
        cmd.append(srcPath).append(" ");
        cmd.append(destPath);
        try {
            Runtime.getRuntime().exec(cmd.toString());
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception{
        //设置纸张大小: A4, Letter, etc.
        String pageSize = "A4";
        //需要生成PDF的URL,这样也可以是页面的本地地址
        String srcPath = "http://www.baidu.com";
        //String srcPath = "D:/index.html";
        //生成后存放路径
        String destPath = "D:/wkhtmltopdf/bin/baidu.pdf";
        convert(pageSize, srcPath, destPath);
    }
}

(二)Linux安装和使用示例

        1、Linux 安装 (示例使用系统版本:CentOS7)

        这里下载 wkhtmltox-0.12.5-1.centos7.x86_64.rpm 最新版本

        2、将rpm包上传至服务器,将包移动到opt目录下

[root@localhost ~]# mv wkhtmltox-0.12.5-1.centos7.x86_64.rpm /opt/

        3、安装

        注意:安装过程中可能会出现openssl版本过低安装失败问题,只需安装或升级openssl即可

#安装
[root@localhost opt]# rpm -ivh wkhtmltox-0.12.5-1.centos7.x86_64.rpm
错误:依赖检测失败:
	xorg-x11-fonts-75dpi 被 wkhtmltox-1:0.12.5-1.centos7.x86_64 需要
#安装需要的依赖
[root@localhost opt]# yum install xorg-x11-fonts-75dpi
#安装完成继续执行上一条命令
[root@localhost opt]# rpm -ivh wkhtmltox-0.12.5-1.centos7.x86_64.rpm
准备中...                          ################################# [100%]
正在升级/安装...
   1:wkhtmltox-1:0.12.5-1.centos7     ################################# [100%]
#安装完成

        4、测试

[root@localhost opt]# wkhtmltopdf http://www.baidu.com /home/baidu.pdf
Loading pages (1/6)
Counting pages (2/6)                                               
Resolving links (4/6)                                                       
Loading headers and footers (5/6)                                           
Printing pages (6/6)
Done

        5、查看

[root@localhost home]# ll
总用量 32
-rw-r--r--.  1 root   root   26739 12月 27 12:04 baidu.pdf

        6、在Linux 环境下使用 java 代码实现

        linux 环境下,只需要将安装路径替换windows的软件安装路径,请求参数根据实际文件或地址路径填写即可,这里还可以将安装路径配置在配置文件里方便维护,下面代码可以作为一个工具类对外提供服务。

public class HtmlToPDFUtils {

    //wkhtmltopdf Linux安装路径
    public static final String toPdfTool = "/usr/local/bin/wkhtmltopdf";


    /**
	 * html转pdf
	 * @param srcPath html路径,可以是硬盘上的路径,也可以是网络路径
	 * @param destPath pdf保存路径
	 * @return 转换成功返回true
	 */
	public static boolean convert(String pageSize, 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 ");
		cmd.append(pageSize);
		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();
		}catch(Exception e){
			result = false;
			e.printStackTrace();
		}
		
		return result;
	}
}

        接收Process的输入和错误信息时,需要创建另外的线程,否则当前线程会一直等待

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
/**
 * 当java调用wkhtmltopdf时,用于获取wkhtmltopdf返回的内容
 */
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);
			String line = null;
			while ((line = br.readLine()) != null) {
				System.outlprintln(line.toString()); //输出内容
			}
		}catch (IOException e){
			e.printStackTrace();
		}
	}
}

 

 

 

 

 


版权声明:本文为aiyabeetle原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。