java项目中用到了html转pdf的需求,现在写一个自己认为最优方案的总结,虽然还是有一些小的bug
为了保证中文的支持需要在被转换的html添加body的添加中文字体样式,保持这个字体和后边转换pdf的字体一致就可以了,不需要必须是SimSun字体
body{
font-family:SimSun;
}
下面放上jar包的引用pom
注意:org.xhtmlrenderer.core-renderer.R8的jar包,其实需要做一些修改,直接用的话不支持中文换行,可以点击下载支持中文换行的jar包,修改jar包名字替掉R8的jar包
org.xhtmlrenderer
core-renderer
R8
org.apache.commons
commons-lang3
3.0
com.itextpdf
itextpdf
5.5.10
com.itextpdf
html2pdf
2.0.0
这种方式对html里的代码样式要求比较严格,类似xhtml的标准,要求html中的标签都是闭合的,像meta和link这样的标签以及空格 ;这类的转义符都会导致转换pdf报错,因此最好在之前将html代码进行处理,以下是处理代码:
import java.io.File;
import java.io.FileInputStream;
import com.itextpdf.html2pdf.jsoup.Jsoup;
import com.itextpdf.html2pdf.jsoup.nodes.Document;
import com.itextpdf.html2pdf.jsoup.nodes.Entities;
public class HtmlToXHtmlJsoup {
public static String html2xhtml(String html) {
Document doc = Jsoup.parse(html);
doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml).escapeMode(Entities.EscapeMode.xhtml);
return doc.html();
}
public static void main(String[] args) throws Exception {
// File file = new File("E:\\html2xhtml.html");
File file = new File("report01.html");
FileInputStream input = new FileInputStream(file);
int size = input.available();
byte[] buff = new byte[size];
input.read(buff);
input.close();
String html = new String(buff, "utf-8");
System.out.println("============html===========