itext转html为pdf遇到的问题
记录一下使用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文件效果如下:

itext转html为pdf遇到的问题的更多相关文章
- iText框架(生成pdf文档)
1.创建一个itext的简单示例 a.导包(pom.xml文件) <dependencies> <dependency> <groupId>com.lowagie& ...
- 用itext合并多个pdf文件【转】【补】
java代码 package c; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arra ...
- Java使用IText(VM模版)导出PDF
Java使用IText(VM模版)导出PDF: public String createPDF(ProjectManageBase projectManageBase) { Map map = new ...
- 【转】Java通过IText导出word和pdf
原帖地址:http://blog.csdn.net/zwx19921215/article/details/34439851 最近做的项目中需要用到把Highcharts图表导出word和pdf的功能 ...
- wkhtmltopdf+itext实现html生成pdf文件的打印下载(适用于linux及windows)
目中遇到个根据html转Java的功能,在java中我们itext可以快速的实现pdf打印下载的功能,在itext中我们一般有以下三中方式实现 配置pdf模板,通过Adobe Acrobat 来设置域 ...
- 利用itext将html转为pdf
亲测代码没有问题,需要注意细节已经标注:需要jar包:iText-2.0.8.jar:core-renderer-R8.jar: core-renderer-R8.jar下载地址:http://cen ...
- Java使用IText(VM模版)导出PDF,IText导出word(二)
===============action=========================== //退款导出word public void exportWordTk() throws IOE ...
- 在spring boot 中使用itext和itextrender生成pdf文件
转载请注明出处 https://www.cnblogs.com/majianming/p/9539376.html 项目中需要对订单生成pdf文件,在第一版本其实已经有了比较满意的pdf文档,但是还是 ...
- 【Java】itext根据模板生成pdf(包括图片和表格)
1.导入需要的jar包:itext-asian-5.2.0.jar itextpdf-5.5.11.jar. 2.新建word文档,创建模板,将文件另存为pdf,并用Adobe Acrobat DC打 ...
随机推荐
- 使用maven插件生成grpc所需要的Java代码
1.首先需要编写自己需要的.proto文件,本文重点不在这里,.proto可以参考grpc官方例子 https://grpc.io/docs/quickstart/java.html 2.创建自己的J ...
- Mysql自学笔记
SQL(strucut query language) DDL (数据库定义语言)DML (数据库操作语言)DCL (数据库的控制语言)DTL (数据库的高级语言)查看版本的函数select vers ...
- XStream轻松转换xml和java对象
首先引入所需的jar: xstream-1.4.9.xpp3_min-1.1.4c.dom4j-1.6.1, 或用maven管理jar包时在pom.xml中添加: <!-- https://mv ...
- 获取已安装app的bundle id
备注:以下是私有api 苹果审核会被拒绝. 导入头文件 #import <objc/runtime.h> /// 获取其他APP信息(iOS11无效) + (NSArray *)getOt ...
- Android Studio Gradle编译时『No resource found that matches the given name』解决方法(windows系统的坑)
* 最近帮团队同事配置gradle时,发现一个非常奇怪的问题:> * 同样的gradle配置的项目,只是修改了一个项目的名称,竟然会出现以下奇怪问题: ## 现象1. 一个编译完全OK,另外一个 ...
- spring mvc 返回xml格式数据
1.问题 : 因为业务需要,需要发送xml格式的数据,使用spring mvc 自己解析,就不用费心去自己搞这些东西. 2.解决: 新建一个实体类,直接在实体类中添加注解即可,如下: @XmlRoot ...
- 第二十一篇 json,picklz,xml模块
Json模块 Json模块比较简单,仅有四个方法dumps()和loads()方法,dump()和load()方法,但是却非常的常用,实用性极强. 如果要在不同的编程语言之间传递对象,就必须把对象序列 ...
- 用node是踩过的一些坑
1.http.request抓取数据时,response的“data”回调事件返回的数据不完整 问题原因:因为“data"事件返回是chunk,就是说是一块块连续的数据 解决的办法:在”da ...
- LB
LB(LBaaS)及Load Balance as a Service是 Neutron 提供的一项高级网络服务. LBaaS 允许租户在自己的网络中创建和管理 load balancer,load ...
- 关于iframe的使用 以及自适应页面高度
1. <a href="port" target="frame_view">港口资料</a> <iframe id="e ...