本文介紹如何在Java程式中将html檔案轉換成PDF檔案。轉換時,需要注意以下兩點:
一、需要使用轉換插件
可根據不同的系統來下載下傳對應的插件,下載下傳位址:windows-x86.zip, windows-x64.zip, macosx_x64.zip, 及linux_x64.zip,下載下傳後需要将插件包解壓到本地指定檔案夾路徑。
二、需要使用到PDF庫,Spire.PDF for Java 版本: 3.6.6及以後的新版本
可通過2種方法導入jar:
1. 可以手動下載下傳jar包,并解壓将lib檔案夾下的jar檔案導入Java程式;
2. 建立Maven項目程式,并在pom.xml檔案中配置Maven倉庫路徑,并指定Spire.PDF for Java的Maven依賴,然後導入jar。
最終jar檔案導入效果如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLxETO2QzM4kDOtAzM3gjM4ADNxgjM4ADMyAjMtATOwYDM38CX4ADMyAjMvwFM5AjNwczLcd2bsJ2Lc12bj5ycn9Gbi52YuAjMwIzZtl2Lc9CX6MHc0RHaiojIsJye.png)
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;
public class HtmlToPDF {
public static void main(String[] args) {
//定義需要轉換的HTML
String url = "https://www.baidu.com/";
//轉換後的結果文檔(結果文檔儲存在Java項目程式檔案下)
String fileName = "HtmlToPDF.pdf";
//解壓後的插件本地位址(這裡是把插件包放在了Java項目檔案夾下,也可以自定義其他本地路徑)
String pluginPath = "C:\\Users\\Administrator\\IdeaProjects\\Conversion_PDF\\plugins-windows-x64";
HtmlConverter.setPluginPath(pluginPath);
//調用方法轉換到PDF并設定PDF尺寸
HtmlConverter.convert(url, fileName, true, 1000, new Size(700f, 800f), new PdfMargins(0));
}
}
Html轉PDF效果如下,保留了原html格式、超連結等等:
(完)