记录一下使用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文件效果如下:

最新文章

  1. Angular 2.0 的设计方法和原则
  2. 绿色 或者 免安装 软件 PortableApps
  3. artTemplate 介绍
  4. JQuery怎么实现页面刷新后保留鼠标点击样式的方法
  5. codeforces #310 div1 A
  6. 转:iOS 7人机界面准则
  7. 有关DeadLock的文章列表
  8. 错误代码: 1582 Incorrect parameter count in the call to native function &#39;str_to_date&#39;
  9. CALayer简介
  10. Bootstrap 常用属性
  11. JDK动态代理浅析
  12. MATLAB GUI设计(线性卷积和循环卷积的比较--笔记)
  13. python 冒泡、二分查找
  14. 如何进行Apache虚拟机设置
  15. 【Linux常见问题】SecureCRT 终端连接密钥交换失败错误
  16. CentOS7 cannot find a valid baseurl for repo base
  17. ABP框架系列之四十一:(Nuget-Packages-Nuget包)
  18. 一文看尽 Raft 一致性协议的关键点
  19. css,js移动资源
  20. vue.js devtools-------调试vue.js的开发者插件

热门文章

  1. struts2学习笔记一
  2. JAVA大作业汇总3
  3. 安装sql server
  4. 关于==和equals()方法&amp;Java中string与char如何转换&amp;String,StringBuffer
  5. Tuxedo 介绍与安装
  6. 洛谷P1189&#39;SEARCH&#39;
  7. PHP Warning: File upload error - unable to create a temporary file in Unknown on line 0
  8. NO9——线段相关
  9. not1,not2,bind1st,bind2nd
  10. lintcode-96-链表划分