最近做了一个用ITextRenderer实现的html转pdf的事例,其中遇到了很多小问题,在此一方面分享一下,另一方面记录一下以便下次需要时观看
jar包 提供gradle依赖
compile 'com.itextpdf:itext-asian:5.2.0'
compile 'com.itextpdf.tool:xmlworker:5.5.6'
compile('org.xhtmlrenderer:flying-saucer-pdf-itext5:9.0.8'){
exclude group: 'com.lowagie'
}
compile 'com.lowagie:iTextAsian:2.1.7'java代码
public class ITextHtmlToPdf {
static final String inputfileName = "D://test.html";
static final String outputfileName = "D://test.pdf";
static final String FontsName = "C:/Windows/fonts/simsun.ttc";
public int HtmlToPdf() throws IOException, DocumentException{
String url = new File(inputfileName).toURI().toURL().toString();
OutputStream os = new FileOutputStream(outputfileName);
ITextRenderer renderer = new ITextRenderer();
// 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(FontsName, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 解决图片的相对路径问题
renderer.getSharedContext().setBaseURL("file:/D:/");
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
return 1;
}
}
3.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css" mce_bogus="1">body {font-family: SimSun;}</style>
</head>
<body>
<img src="timg/a.jpg" alt="你好" />
<div>支持中文!</div>
</body>
</html>
4.小问题
①若报类找不到错误。可能是'org.xhtmlrenderer:flying-saucer-pdf-itext5:9.0.8'该包过期尝试更换
②中文问题。支持中文则需引入亚洲文字包compile 'com.lowagie:iTextAsian:2.1.7'
html中该部分必须存在
<head>
<style type="text/css" mce_bogus="1">body {font-family: SimSun;}</style>
</head>
而且样式中的字体(这里的font-family: SimSun)必须在java代码代码中加入(fontResolver.addFont(“C:/Windows/fonts/simsun.ttc”, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
),字体应当对应,否则都会造成中文字不显示