java通過html轉pdf
阿新 • • 發佈:2019-01-22
HTML轉PDF工具(wkhtmltopdf)介紹,支援widows和linux
wkhtmltopdf下載地址:連結:http://pan.baidu.com/s/1jIkk9Wa 密碼:ljn6
cmd用法:
java用法:
package com.yanhui.test;
import java.io.*;;
public class HtmlToPdf {
private static final String TOPDFTOOL = "D://Program Files//wkhtmltopdf//bin//wkhtmltopdf.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();
}
//c:\wkhtmltopdf.exe http://www.csdn.net c:\csdn.pdf"
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("HTML2PDF成功,引數---html路徑:{},pdf儲存路徑 :{}"+new Object[] {srcPath, destPath });
} catch (Exception e) {
System.out.println(("HTML2PDF失敗,srcPath地址:{},錯誤資訊:{}"));
result = false;
}
return result;
}
public static void main(String[] args) {
String htmlPath = "http://www.baidu.com";
String pdfPath = "D://testpdf2.pdf";
HtmlToPdf.convert(htmlPath, pdfPath );
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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);
br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
全CSDN的豐(好)色(se)部落格,這裡有書本看不到的Java技術,電影院禁播的電影,歡迎關注QQ群494808400