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打 ...
随机推荐
- FIFO的使用场景
(1) 数据的缓冲.如模型图所示,如果数据的写入速率高,但间隔大,且会有突发;读出速率小,但相对均匀.则通过设置相应深度的FIFO,可以起到数据暂存的功能,且能够使后续处理流程平滑,避免前级突发时,后 ...
- JavaScript---设计模式简介
概念 设计模式(Design pattern)是一套被反复使用.思想成熟.经过分类和无数次实战设计经验的总结的.使用设计模式是为了让系统代码可重用.可扩展.可解耦.更容易被人理解且能保证代码的可靠性. ...
- OrCAD创建原理图符号图
1. 首先创建一个库 2. 右键新创建的库,添加新的器件New Part 3. 修改器件属性 4. 添加引脚 添加完引脚之后如图,其中双击引脚,即可修改引脚名字和序号 5. 添加符号的外形 添加完外形 ...
- 存一些有用的CSS
reset ;} table{} fieldset,img{} address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;fon ...
- 各种网站,app的手机号绑定真坑爹
各种网站,app的手机号绑定真坑爹,无力吐槽,哎
- Android adb shell启动应用程序的方法
在Android中,除了从界面上启动程序之外,还可以从命令行启动程序,使用的是命令行工具am. usage: am [subcommand] [options] start an Activity: ...
- CS229 1
1.机器学习 机器学习是工具,具体应用到某个实际场景下,才是目的. 2.分类 a 监督学习,包括回归(regression),分类(classification).回归问题,数据可以是连续或者离散,分 ...
- 使用pyinstaller将Python打包为exe文件
当我们完成一个Python项目或一个程序时,希望将Python的py文件打包成在Windows系统下直接可以运行的exe程序,那么pyInstaller就是一个很好的选择.pyInstaller可以将 ...
- HTML5 本地存储Web Storage简单了解
HTML5本地存储规范,定义了两个重要的API :Web Storage 和 本地数据库Web SQL Database. 本地存储Web Storage 实际上是HTML4的cookie存储机 ...
- P2384洛谷 最短路
题目描述 给定n个点的带权有向图,求从1到n的路径中边权之积最小的简单路径. 输入输出格式 输入格式: 第一行读入两个整数n,m,表示共n个点m条边. 接下来m行,每行三个正整数x,y,z,表示点x到 ...