記錄一下使用itext將html文件轉為pdf文件遇到的一些問題
1、中文不顯示
原因:itext默認不支持中文
解決方法:引入中文字體
需要注意的是在java代碼中設置好中文字體后,還需要在html引用該字體,否則不會起效果。


2、css不起作用
原因:css文件使用的是相對路徑
解決方法:將相對路徑改為絕對路徑或者將css寫在html文件內部
3、html內容轉換為pdf后,內容顯示不全
原因:
解決方法:在html文件中設定紙張大小,如A4紙張@page{size:a4}

具體請參考以下代碼
首先在pom.xml文件中引入itext相關jar包
<!--itext--> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>org.xhtmlrenderer</groupId> <artifactId>core-renderer</artifactId> <version>R8</version> </dependency>
實現將html文件轉換為pdf文件代碼如下:
package com.lnjecit.util; import com.lowagie.text.pdf.BaseFont; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ResourceUtils; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.*; import java.net.MalformedURLException; /** * Pdf處理工具類 * * @author * @create 2017-12-18 21:25 **/ public class PdfUtil { protected static Logger logger = LoggerFactory.getLogger(PdfUtil.class); /** * * @param htmlFile html文件存儲路徑 * @param pdfFile 生成的pdf文件存儲路徑 * @param chineseFontPath 中文字體存儲路徑 */ public static void html2pdf(String htmlFile, String pdfFile, String chineseFontPath) { // step 1 String url; OutputStream os = null; try { url = new File(htmlFile).toURI().toURL().toString(); os = new FileOutputStream(pdfFile); ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(url); // 解決中文不顯示問題 ITextFontResolver fontResolver = renderer.getFontResolver(); fontResolver.addFont(chineseFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); renderer.layout(); renderer.createPDF(os); } catch (MalformedURLException e) { logger.warn(e.toString(), e); } catch (FileNotFoundException e) { logger.warn(e.toString(), e); } catch (com.lowagie.text.DocumentException e) { logger.warn(e.toString(), e); } catch (IOException e) { logger.warn(e.toString(), e); } finally { if(os != null) { try { os.close(); } catch (IOException e) { logger.warn(e.toString(), e); } } } } public static void main(String[] args) { try { //html文件路徑 String htmlFilePath = "E:\\projects\\learn\\spring-boot\\springboot-learn\\springboot-learn\\springboot-poi\\src\\main\\resources\\templates\\index.html"; // 中文字體存儲路徑 String chineseFontPath = "E:\\projects\\learn\\spring-boot\\springboot-learn\\springboot-learn\\springboot-poi\\src\\main\\resources\\Fonts\\simsun.ttc"; // html轉pdf html2pdf(htmlFilePath,"E:\\projects\\learn\\spring-boot\\springboot-learn\\springboot-learn\\springboot-poi\\src\\main\\resources\\templates\\index.pdf", chineseFontPath); System.out.println("轉換成功!"); } catch (Exception e) { logger.error("html轉換為pdf失敗", e); } } }
測試的html內容如下:
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>認識table表標簽</title> <style type="text/css"> /*解決html轉pdf文件中文不顯示的問題*/ body { font-family: SimSun; } /*設定紙張大小*/ /* A4紙 */ /* @page{size:210mm*297mm} */ @page{size:a4} p { color: red; } </style> </head> <body> <table border="1px"> <caption>我的標題</caption> <tbody> <tr> <th>班級</th> <th>學生數</th> <th>平均成績</th> <th>班級</th> <th>學生數</th> <th>平均成績</th> <th>班級</th> <th>學生數</th> <th>平均成績</th> </tr> <tr> <td>一班</td> <td>30</td> <td>89</td> <td>一班</td> <td>30</td> <td>89</td> <td>一班</td> <td>30</td> <td>89</td> </tr> <tr> <td>一班</td> <td>30</td> <td>89</td> <td>一班</td> <td>30</td> <td>89</td> <td>一班</td> <td>30</td> <td>89</td> </tr> <tr> <td>一班</td> <td>30</td> <td>89</td> <td>一班</td> <td>30</td> <td>89</td> <td>一班</td> <td>30</td> <td>89</td> </tr> </tbody> </table> <p> 《俠客行》<br/> 年代: 唐 作者: 李白<br/> 趙客縵胡纓,吳鈎霜雪明。銀鞍照白馬,颯沓如流星。 十步殺一人,千里不留行。事了拂衣去,深藏身與名。 閑過信陵飲,脫劍膝前橫。將炙啖朱亥,持觴勸侯嬴。 三杯吐然諾,五岳倒為輕。眼花耳熱后,意氣素霓生。 救趙揮金槌,邯鄲先震驚。千秋二壯士,煊赫大梁城。 縱死俠骨香,不慚世上英。誰能書閤下,白首太玄經。 </p> </body> </html>
package com.lnjecit.util; import com.lowagie.text.pdf.BaseFont; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ResourceUtils; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.*; import java.net.MalformedURLException; /** * Pdf處理工具類 * * @author * @create 2017-12-18 21:25 **/ public class PdfUtil { protected static Logger logger = LoggerFactory.getLogger(PdfUtil.class); /** * * @param htmlFile html文件存儲路徑 * @param pdfFile 生成的pdf文件存儲路徑 * @param chineseFontPath 中文字體存儲路徑 */ public static void html2pdf(String htmlFile, String pdfFile, String chineseFontPath) { // step 1 String url; OutputStream os = null; try { url = new File(htmlFile).toURI().toURL().toString(); os = new FileOutputStream(pdfFile); ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(url); // 解決中文不顯示問題 ITextFontResolver fontResolver = renderer.getFontResolver(); fontResolver.addFont(chineseFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); renderer.layout(); renderer.createPDF(os); } catch (MalformedURLException e) { logger.warn(e.toString(), e); } catch (FileNotFoundException e) { logger.warn(e.toString(), e); } catch (com.lowagie.text.DocumentException e) { logger.warn(e.toString(), e); } catch (IOException e) { logger.warn(e.toString(), e); } finally { if(os != null) { try { os.close(); } catch (IOException e) { logger.warn(e.toString(), e); } } } } public static void main(String[] args) { try { //html文件路徑 String htmlFilePath = "E:\\projects\\learn\\spring-boot\\springboot-learn\\springboot-learn\\springboot-poi\\src\\main\\resources\\templates\\index.html"; // 中文字體存儲路徑 String chineseFontPath = "E:\\projects\\learn\\spring-boot\\springboot-learn\\springboot-learn\\springboot-poi\\src\\main\\resources\\Fonts\\simsun.ttc"; // html轉pdf html2pdf(htmlFilePath,"E:\\projects\\learn\\spring-boot\\springboot-learn\\springboot-learn\\springboot-poi\\src\\main\\resources\\templates\\index.pdf", chineseFontPath); System.out.println("轉換成功!"); } catch (Exception e) { logger.error("html轉換為pdf失敗", e); } } }
轉換前的html頁面效果如下

轉換后的pdf文件效果如下:

