Java實(shí)現(xiàn)HTML轉(zhuǎn)PDF的兩款工具(itext-pdfhtml和x-easypdf)介紹與使用
01 引言
之前在前文中介紹了三款Html轉(zhuǎn)PDF的工具。這不,又發(fā)現(xiàn)了兩款類似的工具,整理一下分享給大家。
02 itext-pdfhtml-java

2.1 簡(jiǎn)介
iText pdfHTML是iText7套件的一個(gè)附加組件,專門用于將HTML和CSS內(nèi)容轉(zhuǎn)換為PDF文檔。它基于iText核心PDF生成引擎,提供了高質(zhì)量的HTML到PDF轉(zhuǎn)換功能。性能表現(xiàn)非常優(yōu)異。
主要特性:
- 完整的
HTML5和CSS3支持:能夠處理現(xiàn)代網(wǎng)頁(yè)布局和樣式 - 字體嵌入:自動(dòng)處理Web字體和系統(tǒng)字體
- 響應(yīng)式設(shè)計(jì):支持媒體查詢和響應(yīng)式布局
- 高保真轉(zhuǎn)換:保持HTML內(nèi)容的視覺保真度
- Java原生:專為Java生態(tài)系統(tǒng)設(shè)計(jì)
GitHub地址:github.com/itext/itext-pdfhtml-java
官方地址:itextpdf.com/products/convert-html-css-to-pdf-pdfhtml
2.2 案例
使用起來(lái)也非常簡(jiǎn)單,下面官方的案例:

Maven依賴:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>6.2.1</version>
</dependency>
實(shí)踐代碼:
@RequestMapping("index6")
public void index6(Model model, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Map<String, Object> item = new HashMap<>();
item.put("image1", "http://example.com/2eb97.jpg");
item.put("image2", "http://example.com/2f9c3.jpg");
item.put("vehicleName", "路虎Defender[衛(wèi)士](進(jìn)口)2023款Defender130 48V[衛(wèi)士 130 48V] 3.0T手自-體P400 HSE");
item.put("brandName", "路虎");
item.put("seriesName", "Defender[衛(wèi)士]");
item.put("modelYear", "2023款");
item.put("licenseYear", SDF.format(new Date()));
item.put("displayMileage", DF.format(new BigDecimal("9657")));
item.put("dealDate", SDF.format(new Date()));
item.put("dealPrice", DF.format(new BigDecimal("702400")));
item.put("licenseCode", "滬A952714");
list.add(item);
}
model.addAttribute("list", list);
Map<String, Object> map = new HashMap<>();
map.put("list", list);
Context context = new Context(Locale.getDefault(), map);
String htmlContent = templateEngine.process("index", context);
System.out.println(htmlContent);
// ---------------------------------------------------
/*itext-html2pdf*/
ConverterProperties properties = new ConverterProperties();
FontProvider fontProvider = new FontProvider();
fontProvider.addSystemFonts();
// fontProvider.addFont("C:\\Windows\\Fonts\\simhei.ttf");
// 添加系統(tǒng)字體
properties.setFontProvider(fontProvider);
HtmlConverter.convertToPdf(htmlContent, response.getOutputStream(), properties);
}
同樣默認(rèn)是不支持中文的,需要通過(guò)FontProvider添加指定的字體。fontProvider.addSystemFonts();直接添加系統(tǒng)字體,也可以通過(guò)addFont()添加自定義字體。頁(yè)面必須聲明字體,否則會(huì)出現(xiàn)亂碼。
03 x-easypdf

3.1 簡(jiǎn)介
x-easypdf是一個(gè)java語(yǔ)言簡(jiǎn)化處理pdf的框架,包含fop模塊與pdfbox模塊,fop模塊以創(chuàng)建功能為主,基于xsl-fo模板生成pdf文檔,以數(shù)據(jù)源的方式進(jìn)行模板渲染;pdfbox模塊以編輯功能為主,對(duì)標(biāo)準(zhǔn)的pdfbox進(jìn)行擴(kuò)展,添加了成噸的功能。
Html轉(zhuǎn)Pdf是pdfbox模塊下的一個(gè)轉(zhuǎn)化器的功能,是基于 playwright 實(shí)現(xiàn)的。而playwright的依賴需要手動(dòng)引入。Playwright是一個(gè)跨語(yǔ)言的瀏覽器自動(dòng)化庫(kù),由Microsoft開發(fā)。雖然主要用于端到端測(cè)試,但其強(qiáng)大的PDF生成功能也使其成為HTML轉(zhuǎn)PDF的優(yōu)秀工具。

Gitee地址:gitee.com/dromara/x-easypdf
官網(wǎng)地址:x-easypdf.cn/
3.2 案例
x-easypdf是對(duì)playwrigh的功能做了一層包裝,使用起來(lái)更方便。
Maven依賴
<dependency>
<groupId>org.dromara</groupId>
<artifactId>x-easypdf</artifactId>
<version>3.4.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.53.0</version>
</dependency>
實(shí)踐代碼01
@RequestMapping("index10")
public void index10(HttpServletResponse response) throws IOException {
// 獲取html轉(zhuǎn)換器
HtmlConvertor convertor = PdfHandler.getDocumentConvertor().getHtmlConvertor();
Document pdf = convertor.toPdf("http://127.0.0.1:8080/page/index");
pdf.save(response.getOutputStream());
}
注意事項(xiàng)
playwrigh是基于瀏覽器引擎的,首次調(diào)用會(huì)下載默認(rèn)的瀏覽器,下載完成之后,后續(xù)的使用就流暢了。而且默認(rèn)支持中文,因?yàn)槭褂脼g覽器引擎,所以對(duì)于Html和Css支持較好。但是消耗資源較高。
但是這里convertor.toPdf()目前支持傳入地址和文件。不支持直接html內(nèi)容直接轉(zhuǎn)化的。但是playwrigh本身是支持的。
小編已經(jīng)給x-easypdf作者提了issues:gitee.com/dromara/x-e…
**注意:**截止發(fā)稿,官方已經(jīng)在3.5.0版本支持了html內(nèi)容轉(zhuǎn)Pdf。

實(shí)戰(zhàn)代碼02
使用模板引擎的方式:

官網(wǎng)地址:x-easypdf.cn/guide/pdfbox/advance/templater
依然是建立在playwrigh基礎(chǔ)之上。
@RequestMapping("index12")
public void index12(HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Map<String, Object> item = new HashMap<>();
item.put("image1", "http://example.com/2eb97.jpg");
item.put("image2", "http://example.com/2f9c3.jpg");
item.put("vehicleName", "路虎Defender[衛(wèi)士](進(jìn)口)2023款Defender130 48V[衛(wèi)士 130 48V] 3.0T手自-體P400 HSE");
item.put("brandName", "路虎");
item.put("seriesName", "Defender[衛(wèi)士]");
item.put("modelYear", "2023款");
item.put("licenseYear", SDF.format(new Date()));
item.put("displayMileage", DF.format(new BigDecimal("9657")));
item.put("dealDate", SDF.format(new Date()));
item.put("dealPrice", DF.format(new BigDecimal("702400")));
item.put("licenseCode", "滬A952714");
list.add(item);
}
Map<String, Object> map = new HashMap<>();
map.put("list", list);
ThymeleafTemplater templater = PdfHandler.getDocumentTemplater().getThymeleafTemplater();
templater.setTemplatePath("templates");
templater.setTemplateName("index.html");
templater.setTemplateData(map);
// 獲取 html 內(nèi)容
String content = templater.getHtmlContent();
System.out.println(content);
// 轉(zhuǎn)換文檔
Document document = templater.transform();
document.save(response.getOutputStream());
}
這里需要說(shuō)明的是:由于x-easypdf自行解析了Thymeleaf模版,所以無(wú)法使用spring-boot-starter-thymeleaf的配置。templatePath和templateName都需要寫完整。templatePath指classpath下的路徑。
模板引擎可能會(huì)出現(xiàn)nested exception is java.lang.NoClassDefFoundError: ognl/PropertyAccessor的錯(cuò)誤,需要引入ognl,且版本不能超過(guò)3.2。從 3.2 開始,會(huì)報(bào)java.lang.NoClassDefFoundError: ognl/DefaultMemberAccess。有效版本:
<dependency> <groupId>ognl</groupId> <artifactId>ognl</artifactId> <version>3.1.28</version> </dependency>
邊距可以通過(guò)打印樣式控制:
@page {
size: A4;
margin: 20px;
}
3.3playwrigh原生寫法
@RequestMapping("index11")
public void index11(HttpServletResponse response) throws IOException {
try (Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch()) {
BrowserContext context = browser.newContext();
Page page = context.newPage();
// 從HTML內(nèi)容生成PDF
page.setContent("<h1>Hello, Playwright!</h1>");
byte[] pdf = page.pdf();
ByteArrayInputStream bais = new ByteArrayInputStream(pdf);
IOUtils.copy(bais, response.getOutputStream());
}
}
04 小結(jié)
iText pdfHTML內(nèi)存占用低,轉(zhuǎn)換速度快,適合服務(wù)器端批量處理。而Playwright需要更多資源,但渲染質(zhì)量極高,適合對(duì)視覺保真度要求高的場(chǎng)景,所以x-easypdf也是一樣的。如果只是針對(duì)Html轉(zhuǎn)Pdf的服務(wù)端轉(zhuǎn)化的場(chǎng)景iText pdfHTML的優(yōu)勢(shì)更明顯一下,關(guān)鍵它快!
也有粉絲朋友留言說(shuō)jasperreports也很好用,小編也試了一下。jasperreports需要加載特定的模板,也許是因?yàn)椴皇呛苁煜ぃ闷饋?lái)感覺有點(diǎn)別扭。這里就不推薦了,有興趣的可以去試試!
以上就是Java實(shí)現(xiàn)HTML轉(zhuǎn)PDF的兩款工具(itext-pdfhtml和x-easypdf)介紹與使用的詳細(xì)內(nèi)容,更多關(guān)于Java HTML轉(zhuǎn)PDF的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
關(guān)于SpringBoot中的XA事務(wù)詳解
這篇文章主要介紹了關(guān)于SpringBoot中的XA事務(wù)詳解,事務(wù)管理可以確保數(shù)據(jù)的一致性和完整性,同時(shí)也可以避免數(shù)據(jù)丟失和沖突等問(wèn)題。在分布式環(huán)境中,XA?事務(wù)是一種常用的事務(wù)管理方式,需要的朋友可以參考下2023-07-07
Java中隊(duì)列Queue和Deque的區(qū)別與代碼實(shí)例
學(xué)過(guò)數(shù)據(jù)結(jié)構(gòu)的,一定對(duì)隊(duì)列不陌生,java也實(shí)現(xiàn)了隊(duì)列,下面這篇文章主要給大家介紹了關(guān)于Java中隊(duì)列Queue和Deque區(qū)別的相關(guān)資料,需要的朋友可以參考下2021-08-08
Springboot3整合Elasticsearch8(elasticsearch-java)最佳實(shí)踐
文章推薦使用Elasticsearch官方新客戶端(ElasticsearchJavaAPIClient)替代已廢棄的RestHighLevelClient,對(duì)比SpringDataElasticsearch和easy-es的優(yōu)缺點(diǎn),詳解SpringBoot3整合步驟及高階用法,強(qiáng)調(diào)新客戶端功能全且適配最新版本,感興趣的朋友一起看看吧2025-07-07
一篇文章讓你徹底學(xué)會(huì)Java之exists()方法
Java中File.exists()方法用于檢查文件或目錄是否存在,是文件操作的前置檢查工具,這篇文章主要介紹了Java之exists()方法的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-07-07
Java?file.delete刪除文件失敗,Windows磁盤出現(xiàn)無(wú)法訪問(wèn)的文件問(wèn)題
使用java實(shí)現(xiàn)手機(jī)短信驗(yàn)證全過(guò)程

