2018-11-16 使用java實現(xiàn)html轉(zhuǎn)pdf

項目中有個需求要把病人的報告轉(zhuǎn)成pdf打印,剛開始在網(wǎng)上找了很多資料各種方法都有最后選擇了wkhtmltopdf。wkhtmltopdf是一個使用webkit網(wǎng)頁渲染引擎開發(fā)的用來將 html轉(zhuǎn)成 pdf的工具,可以跟多種腳本語言進行集成來轉(zhuǎn)換文檔。

因為需要下載插件:

官網(wǎng)地址?http://wkhtmltopdf.org/

wkhtmltopdf把html轉(zhuǎn)成pdf很簡單,只要在windows命令行中輸入

D:\wkhtmltox\bin\wkhtmltopdf.exe http://www.itdecent.cn c:\test.pdf

這樣就可以把簡書網(wǎng)頁保存到C盤根目錄下了。

在java中調(diào)用wkhtmltopdf的命令Runtime.getRuntime().exec("D:\wkhtmltox\bin\wkhtmltopdf.exe?http://www.itdecent.cn?c:\test.pdf")就可以實現(xiàn)轉(zhuǎn)換。

下面是封裝的工具類

public class HtmlToPdf {

//wkhtmltopdf在系統(tǒng)中的路徑

? ? private static final StringtoPdfTool ="D:\\wkhtmltox\\bin\\wkhtmltopdf.exe";

? ? /**

* html轉(zhuǎn)pdf

*

? ? * @param srcPath? html路徑,可以是硬盤上的路徑,也可以是網(wǎng)絡(luò)路徑

? ? * @param destPath pdf保存路徑

? ? * @return 轉(zhuǎn)換成功返回true

*/

? ? public static boolean convert(String srcPath, String destPath) {

File file =new File(destPath);

? ? ? ? File parent = file.getParentFile();

? ? ? ? //如果pdf保存路徑不存在,則創(chuàng)建路徑

? ? ? ? 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();

? ? ? ? }catch (Exception e) {

result =false;

? ? ? ? ? ? e.printStackTrace();

? ? ? ? }

return result;

? ? }

}

接收Process的輸入和錯誤信息時,需要創(chuàng)建另外的線程,否則當(dāng)前線程會一直等待(在Tomcat中有這種現(xiàn)象)。


最后在項目中調(diào)用即可生成自己想要的pdf

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容