您的位置:首页 > 其它

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

2015-10-03 10:12 357 查看
前几天项目中涉及到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;
  }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: