ITextRenderer_html转换为pdf

最近做了一个用ITextRenderer实现的html转pdf的事例,其中遇到了很多小问题,在此一方面分享一下,另一方面记录一下以便下次需要时观看

  1. 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'

  2. 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);
),字体应当对应,否则都会造成中文字不显示

 

转载于:https://my.oschina.net/zlb1992/blog/511996

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值