php stream_select w3c,使用flying-saucer 实现 html转pdf实现input框select,textarea checkbox等的显示...

com.itextpdf

itextpdf

${itextpdf.version}

com.itextpdf

itext-asian

${itext.asian.version}

中文显示问题解决了,当时碰到了打印表单中input框等不显示的问题。

今天换了个方案使用flying-saucer 实现html转pdf

org.xhtmlrenderer

flying-saucer-pdf-itext5

9.1.1

实现代码如下:

public void html2pdf(String html, File file, String fontDir) throws I18NIllegalArgumentException {

try (OutputStream os = new FileOutputStream(file); ){

ITextRenderer renderer = new ITextRenderer();

ITextFontResolver fontResolver = (ITextFontResolver) renderer.getSharedContext().getFontResolver();

//添加字体库 begin

File f = new File(fontDir);

if (f.isDirectory()) {

File[] files = f.listFiles(new FilenameFilter() {

@Override

public boolean accept(File dir, String name) {

String lower = name.toLowerCase();

return lower.endsWith(".otf") || lower.endsWith(".ttf") || lower.endsWith(".ttc");

}

});

for (int i = 0; i < files.length; i++) {

fontResolver.addFont(files[i].getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

}

}

//添加字体库end

renderer.setDocumentFromString(html);

renderer.layout();

renderer.createPDF(os);

} catch (Exception e) {

throw new I18NIllegalArgumentException(e);

}

}

网上查的都是添加字体的方法都是这样实现的:

ITextFontResolver fontResolver = renderer.getFontResolver();

fontResolver.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

fontResolver.addFont("C:/Windows/Fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

fontResolver.addFont("C:/Windows/Fonts/simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

这样实现有个缺陷:字体的路径都是系统的目录,不同系统(windows,Linux)字体目录不同,对系统依赖太高。

为了解决这个问题:找到字体库文件,复制到项目的目录中,在代码中直接遍历这个目录,添加所有的字体。

注意:页面中字体不能使用中文,需要使用英文名称,而且是大小写敏感的!例如宋体的英文名称是 SimSun(注意不是simsun!,首字母都是大写的)

错误写法:font-family:'宋体' 或者  font-family:'simsun'  或者  font-family: '微软雅黑'

正确写法:font-family:'SimSun' 或者 font-family:'SimHei'或者  font-family:  'Microsoft YaHei'

另外: html的格式要求符合xml格式(即必须有结束标签)

测试:

测试用html代码:

我是标题

*{font-family: 'SimSun';}

我是内容

asdfsdf今晚打老虎

运动睡觉

html浏览器显示结果:

eb37deed92ae3f714c0dea760fc291ea.png

生成的pdf:

d69bfefa62beabb9c690c0f85639f203.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值