說明:藉助wkhtmltopdf 實現網頁導出成pdf
一、下載相關應用
官網地址:https://wkhtmltopdf.org/downloads.html
github:https://github.com/wkhtmltopdf/wkhtmltopdf/releases
二、java導出
package top.cflwork.util;
import java.io.File;
import java.util.Date;
/**
* * Created by chenfeilong on 2019/11/07.
* * 導出pdf
*
*/
public class Wkhtmltopdf {
//wkhtmltopdf 在系統中的路徑
private static final String toPdfTool = "C:\\Users\\DELL\\Downloads\\wkhtmltox-0.12.5-1.msvc2015-win64\\bin\\wkhtmltopdf.exe";
public static void main(String[] args) {
Date date = new Date();
String fileName = String.valueOf(date.getTime()) + ".pdf";
convert("https://www.csdn.net/", "F:\\" + fileName);
}
/**
* * 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 = getFormal();
//html路徑 即目標網頁路徑
cmd.append(" ");
cmd.append(srcPath);
cmd.append(" ");
//pdf保存路徑
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;
}
/**
* * 標準格式
* *
* * @return
*
*/
public static StringBuilder getFormal() {
StringBuilder cmd = new StringBuilder();
//wkhtmltopdf 在系統中的路徑
cmd.append(toPdfTool);
cmd.append(" ");
// cmd.append(" --header-line");//頁眉下面的線
// cmd.append(" --footer-line");//頁腳上面的線
// cmd.append(" --footer-center [page]/[topage]"); //在頁腳中心放置頁碼
// cmd.append(" --header-right 這裏是我們系統的頁眉"); //頁眉中間放置文字
// cmd.append(" --header-html http://localhost:8090/myheader.html"); //頁眉中間放置圖片
// cmd.append(" --header-spacing 5 ");// (設置頁眉和內容的距離,默認0 )
// cmd.append(" --margin-top 20mm "); //設置頁面上邊距 (default 10mm)
// cmd.append(" cover http://localhost:8090/firstPage.html ");
return cmd;
}
public static StringBuilder test1() {
StringBuilder cmd = new StringBuilder();
//wkhtmltopdf 在系統中的路徑
cmd.append(toPdfTool);
// cmd.append(" --cover http://localhost:8090/firstPage.html");
cmd.append(" -T 15mm");
cmd.append(" --header-spacing 5");
cmd.append(" --outline");
cmd.append(" cover http://image.baidu.com");
cmd.append(" ");
return cmd;
}
}