说明:本程序支持windows32 和64 支持UNIX系统 MAC系统
1、首先安装wkhtmltopdf
下载地址:
官网地址: wkhtmltopdf
2、编写程序,并配置安装的wkhtmltopdf路径
package com.example.demo.utils;
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.out.println(line); //输出内容
}
}catch (IOException e){
e.printStackTrace();
}
}
}
package com.example.demo.utils;
import java.io.File;
public class HtmlToPdf2 {
//wkhtmltopdf在系统中的路径
private static final String toPdfTool = "E:\\javasoftware\\htmlToPdf\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";//转图片为wkhtmltopimage.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();
}
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("生成的pdf路径为:"+destPath);
}catch(Exception e){
result = false;
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
convert("http://news.ynet.com/2021/10/11/3371592t2518.html","f:\\test.pdf");
}
}
3、调用方法或直接启动测试