iText 插件将页面以输出流的形式进行pdf下载

    前几天项目中涉及到pdf的下载功能,经过几天的努力已经完成,特意将所涉及到的东西做一总结。

    项目前前后后涉及到几个jar包:itextpdf5.5.6,xmlworker5.5.6,itext-asian5.2.0(linux 服务器上无法显示中文必须此包,windows服务器不需要),这三个包完全可以在

maven repository中取得。

    直接上代码:

       一、

            String path =ServletActionContext.getServletContext().getRealPath("/");
            String HTML = path+"a.sql";

            // 路径 注意linux和windows 反斜线的区别
            HttpServletResponse response= ServletActionContext.getResponse();
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/pdf");
            String pdfName = "本地下载.pdf";
            response.addHeader("Content-Disposition", "attachment;filename="+ new String (pdfName.getBytes("gb2312"),"iso-8859-1"));


            Document document = new Document();

    //此处用outputStream 是做成流下载的样式,如果只需下载到本地,只需替换成本地文件加地址即可
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            document.open();

            //该方法可查看XMLWorkerHelper API文档里面有详细的介绍,ChinaFont是自定义的一个中文类,主要解决于linux 服务器下中文无法显示的问题

            // 方法1和2根据需要选择
            1、XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(HTML),
                    null,Charset.forName("UTF-8"), new ChinaFont());
           //如果是windows服务器可选在下面的方法,不需要自己定义中文类
           2、XMLWorkerHelper.parseXHtml(writer, document,
                    new FileInputStream(HTML), Charset.forName("UTF-8"));
            document.close();
            outputStream.flush();

 

      二、 自定义中文类

    //此类一定要实现 FontProvider接口

    public class ChinaFont implements FontProvider {

        @Override
        public boolean isRegistered(String fontname) {
            return false;
        }

        public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color){
            
            try {
                BaseFont bfChinese;
                bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
                return new Font(bfChinese, size, style, color);
            } catch (DocumentException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
          return null;
      }

转载于:https://www.cnblogs.com/java-zfx2012/p/4853094.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值