支持自定义字体
private static void renderPDF(String html, OutputStream outputStream) throws Exception {
try {
PdfRendererBuilder builder = new PdfRendererBuilder();
addFont(builder, "D:\\font\\");
builder.useUnicodeBidiSplitter(new ICUBidiSplitter.ICUBidiSplitterFactory());
builder.useUnicodeBidiReorderer(new ICUBidiReorderer());
builder.defaultTextDirection(TextDirection.LTR);
builder.useSVGDrawer(new BatikSVGDrawer());
builder.useObjectDrawerFactory(buildObjectDrawerFactory());
//这一段可以忽略、正则处理内容(没有优化)
String h = html.replaceAll("<!--[\\w\\W\r\\n]*?-->", "").replaceAll("(?i)<img+([^>]*?[\\s\"])[(.*?)>]", "<img$1/>").replaceAll(" ", " ").replaceAll("(ng-bind=\"|ng-class=\"|ng-src=\"|ng-style=\")(.*?)\"", "");
builder.withHtmlContent(h, TestcaseRunner.class.getResource("/testcases/").toString());
builder.toStream(outputStream);
builder.run();
} finally {
outputStream.close();
}
}
/**
* 添加字体库
* @param builder
* @param dir
*/
private static void addFont(PdfRendererBuilder builder, String dir) {
File f = new File(dir);
if (f.isDirectory()) {
File[] files = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
String lower = name.toLowerCase();
// lower.endsWith(".otf") || 对otf库的字体支持有问题,暂时屏蔽
return lower.endsWith(".ttf") || lower.endsWith(".ttc");
}
});
for (File subFile:files) {
String fontFamily = subFile.getName().substring(0, subFile.getName().lastIndexOf("."));
builder.useFont(subFile, fontFamily);
}
}
}
支持粗体
for (File subFile:files) {
String fontFamily = subFile.getName().substring(0, subFile.getName().lastIndexOf("."));
//核心代码
//自定义规则 加粗的库 含有"_"
// 700 为bold对应的数值、默认为400
if(fontFamily.indexOf("_") > 0){
builder.useFont(subFile, fontFamily.substring(0, fontFamily.indexOf("_")), 700, FontStyle.NORMAL, true);
}else{
builder.useFont(subFile, fontFamily);
}
}
斜体等类似
追溯源码,一种字体对应多个字体列表(常规、粗体、斜体、粗体_斜体)
根据字体名称_粗体_style 判断优先级,依次筛选