[TOC]
1.实战
引入flying-saucer-pdf-itext5包
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-itext5</artifactId>
<version>9.1.18</version>
</dependency>
实战
/**
* 头
*
* <style>*{font-family:SimSun !important;}</style>
*/
private static final String HTML_HEAD =
"<!DOCTYPE html PUBLIC \" -//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www"
+ ".w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\" > "
+ "<html style=\"height:100%;\"><head><meta http-equiv=\"Content-Type\" "
+ "content=\"text/html;charset=GBK\"/>" + "<style>*{font-family:SimSun;}</style></head>"
+ "<body>";
/**
* 尾
*/
private static final String HTML_TAIL = "</body></html>";
public static void main(String[] args) throws IOException, DocumentException {
String path = "D://pdf.pdf";
String text = "<p style=\"font-family: SimSun;\">天马行空 " + "aaaaaaaaaa</p>" + ""
+ "<p style=\"font-family: SimSun;\">KaiTi楷体</p>";
createPdf(text, path);
}
public static void createPdf(String text, String path) throws IOException, DocumentException {
text = HTML_HEAD + text + HTML_TAIL;
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(text);
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver
.addFont("C:\\Windows\\Fonts\\simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.layout();
File file = new File(path);
try (OutputStream out = new FileOutputStream(file)) {
renderer.createPDF(out);
} catch (Exception e) {
throw e;
}
}
2.中文显示问题
### 1.需要导入字体库
fontResolver.
addFont("C:\\Windows\\Fonts\\simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
2.在style指定font-family
字体样式,如果错误则中文不显示,自己对应的找下
https://www.jianshu.com/p/44ef95b2c86f
3.全局指定中文字体库
<head><style>*{font-family:SimSun;}</style></head>
可以在代码中强制指定字体
*{font-family:SimSun !important;}
4.字体库优先级
多字体之间使用逗号(,)分隔,如果前者没有该字体库,则选择后面的
font-family:SimSun,KaiTi;
如果没有仿宋字体,则选择楷体字体
代码
String path = "D://pdf.pdf";
String text = "<p style=\"font-family: SimSun;\">天马行空 " + "aaaaaaaaaa</p>" + ""
+ "<p style=\"font-family: SimSun;\">KaiTi楷体</p>";
Pattern compile = Pattern.compile("font-family:(.*?);");
Matcher matcher = compile.matcher(text);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String param = matcher.group();
param = param.substring(0, param.length() - 1) + ",hetti;";
matcher.appendReplacement(sb, param);
}
matcher.appendTail(sb);
createPdf(sb.toString(), path);
替换后结果
<p style="font-family: SimSun,hetti;">天马行空 aaaaaaaaaa</p>
<p style="font-family: SimSun,hetti;">KaiTi楷体</p>
网友评论