項目中有個需求要把病人的報告轉(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