Java 将HTML文件转换成PDF(Windows和linux)

核心代码

package lijiong.pdf.htmltopdfv2;

import java.io.IOException;

public class PDFTool {  
  
    //wkhtmltopdf在系统中的路径
    private static final String toPdfTool = "D:/IT/Java/wkhtmltopdf/bin/wkhtmltopdf.exe";
    


    public String getCommand(String htmlName , String pdfName){  
        String system = System.getProperty("os.name");  
        if("Windows XP".equalsIgnoreCase(system)||"Windows 10".equalsIgnoreCase(system)||"Windows 7".equalsIgnoreCase(system))   //xp系统  
            return toPdfTool + " "  + htmlName + " " + pdfName;  
        else  if("Linux".equalsIgnoreCase(system))  //linux 系统  
            return "wkhtmltopdf-amd64 " + htmlName + " " + pdfName;  
        return ""   ;  
    }  
    
    public static void main(String[] args){  
    	PDFTool pdfTool = new PDFTool();  
        String command1 = pdfTool.getCommand("http://www.jikexueyuan.com", "d:/javaSpring.pdf");  
        System.out.println(command1);  
        try {   
            Runtime.getRuntime().exec(command1);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    } 
}  



公司工作文档的需要将HTML格式转换成PDF文档备份,网上也有很多在线工具可以使用,但是大部分工具有些限制且广告太多,在找工具的时候看到Wkhtmltopdf工具可以直接在Linux直接安装使用,Wkhtmltopdf是一个开源的将webkit浏览器把网页生成pdf的开源组件。

根据介绍Wkhtmltopdf有Windows和Linux版本,这里老左直接在CentOS系统中安装和转换看看效果。

第一、Wkhtmltopdf 下载

A - 64位

wget http://download.gna.org/wkhtmltopdf/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz

B - 32位

wget http://download.gna.org/wkhtmltopdf/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-i386.tar.xz

第二、解压、安装

A - 64位

tar -xvf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz

B -32位

tar -xvzf wkhtmltox-0.12.4_linux-generic-i386.tar.xz

根据我们下载版本解压。

cp wkhtmltox/bin/wkhtmltopdf /usr/bin/

将程序拷贝到/usr/bin/目录中,这样可以任意目录执行。

第三、如何使用Wkhtmltopdf

wkhtmltopdf http://www.wpbeginner.com/plugins/7-best-wordpress-backup-plugins-compared-pros-and-cons/ 7-best-wordpress-backup.pdf

这里老左随便找一个页面,然后设置需要转换的HTML页面 和PDF文档。

Linux利用Wkhtmltopdf工具将HTML转换PDF格式文档

执行完毕之后,我们可以在当前目录中看到转换好的PDF文档,可以下载到本地打开看看。



posted @ 2017-09-04 01:44  随风落木  阅读(11)  评论(0编辑  收藏  举报  来源