参考:https://my.oschina.net/960823/blog/1588166
遇到的几个问题:
1. 我这边是html中的数据需要自己填充,所以参考的 FileTypeConvertUtil.html2pdf() 方法就改为了 FileTypeConvertUtil.htmlCode2pdf() 方法如下
/**
* 将HTML代码转成PD格式的文件。html文件的格式比较严格
* @param htmlCode 代码
* @param pdfFile
* @throws Exception
*/
// <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
public static void htmlCode2pdf(String htmlCode, String pdfFile) throws Exception {
// step 1
// step 2
OutputStream os = new FileOutputStream(pdfFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(htmlCode);
// step 3 解决中文支持
ITextFontResolver fontResolver = renderer.getFontResolver();
if("linux".equals(getCurrentOperatingSystem())){
fontResolver.addFont("/usr/share/fonts/chinese/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}else{
fontResolver.addFont("c:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
renderer.layout();
renderer.createPDF(os);
os.close();
System.out.println("create pdf done!!");
}
2. 其中原文章中的 linux下的路径是
/usr/share/fonts/chiness/simsun.ttc 我改为了 chiness -> chinese
3. 因为所用实现方式较严格,所以加入了前缀固定 以及后缀,然后可以专注的做body中的代码生成。
/**
* @description: 生成pdf
* @param: genHtmlByDatas 需要生成的html代码 只是body中的
* @param: targetFile 生成pdf的路径
* @author: wangyf
* @date: 2021/5/26 16:27
*/
public static void genHtml(String genHtmlByDatas, String targetFile) {
StringBuilder htmlCode = new StringBuilder();
htmlCode.append(genBegin());// 前缀
htmlCode.append(genHtmlByDatas);
htmlCode.append(genEnd());// 后缀
try {
FileTypeConvertUtil.htmlCode2pdf(htmlCode.toString(), targetFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private static String genBegin() {
return "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
"<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
"<head>\n" +
"\t<title>测试11231</title>\n" +
"\t<style type=\"text/css\">\n" +
"\t\ttable {\n" +
"\t\t\tborder-collapse: collapse;\n" +
"\t\t\ttable-layout: fixed;\n" +
"\t\t\tword-break:break-all;\n" +
"\t\t\tfont-size: 10px;\n" +
"\t\t\twidth: 100%;\n" +
"\t\t\ttext-align: center;\n" +
"\t\t}\n" +
"\t\ttd {\n" +
"\t\t\tword-break:break-all;\n" +
"\t\t\tword-wrap : break-word;\n" +
"\t\t}\n" +
"\t</style>\n" +
"</head>\n" +
"<body style = \"font-family: SimSun;\">\n"
;
}
private static String genEnd() {
return "\t</body>\n" +
"</html>";
}
4. 但是生成的pdf有分页的问题。我的解决方式是 自己手动控制换页的方式,代码为:
<div style="page-break-after: always;"></div>
5. linux上字体的问题:直接从windows上找到simsun.ttc复制到 linux的目录下就行了,这里面是两个文件,我全选中复制出来变成了一个,没有关系,是simsun.ttc即可。


1652

被折叠的 条评论
为什么被折叠?



