将html(JSP)生成PDF,并可以在浏览器下载

使用itext 将html(JSP)生成PDF,并可以在浏览器下载
其实主要是html生成pdf,jsp想要生成pdf的话需要将jsp动态生成一个html,在将html转成pdf。因为jsp包含有标签头

   <%@ page contentType="text/html;charset=UTF-8" language="java" %>

itext 无法识别这个,就会报错。所以最好先转成html。
后面文章使用jspdf动态转化PDF https://blog.csdn.net/Dcocount/article/details/89674904
下面是代码部分:
生成pdf工具类:html2pdf
String htmlFile:原始的html文件绝对路径
String pdfFile:要生成的pdf的绝对路径
String chineseFontPath:中文字体包资料(我的资源里面有)

     public static void html2pdf(String htmlFile, String pdfFile, String chineseFontPath)  {
       // step 1
     String url;
    OutputStream os = null;
    try {
        url = new File(htmlFile).toURI().toURL().toString();
        os = new FileOutputStream(pdfFile);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        // 解决中文不显示问题
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont(chineseFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        renderer.layout();
        renderer.createPDF(os);
    } catch (MalformedURLException e) {
        logger.warn(e.toString(), e);
    } catch (FileNotFoundException e) {
        logger.warn(e.toString(), e);
    } catch (com.lowagie.text.DocumentException e) {
        logger.warn(e.toString(), e);
    } catch (IOException e) {
        logger.warn(e.toString(), e);
    } finally {
        if(os != null) {
            try {
                os.close();
            } catch (IOException e) {
                logger.warn(e.toString(), e);
            }
        }
    }
}

服务器(下载功能也写在里面)

 @ResponseBody
    @RequestMapping(value = "downloadPDF")
    public void downLoadPDF(HttpServletResponse response){
        //html文件路径
        String htmlFilePath = "F:\\Workspase\\BackController\\src\\main\\webapp\\hello.html";
        // 中文字体存储路径
        String chineseFontPath = "F:\\Workspase\\BackController\\src\\main\\webapp\\WEB-INF\\doc\\simsun.ttc";
        String fileName = "2.pdf";
        OutputStream outputStream = null;
        try {
            // 防止中文乱码
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            //生成pdf文件
            PdfUtil.html2pdf(htmlFilePath,"F:\\Workspase\\BackController\\src\\main\\webapp\\WEB-INF\\doc\\2.pdf",chineseFontPath);
            outputStream.flush();
            int aRead = 0;
            FileInputStream in = new FileInputStream("F:\\Workspase\\BackController\\src\\main\\webapp\\WEB-INF\\doc\\2.pdf");
            ServletOutputStream out = response.getOutputStream();
            //下载功能
            while ((aRead = in.read()) != -1 & in != null) {
                out.write(aRead);
            }
            out.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

另外如果是maven项目,要在pom.xml文件中添加如下配置。如果不是maven项目下载itext包导入项目即可

   <dependency>
      <groupId>com.itextpdf</groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
  </dependency>
   <dependency>
        <groupId>org.xhtmlrenderer</groupId>
        <artifactId>core-renderer</artifactId>
        <version>R8</version>
    </dependency>

另外如果pdf不显示中文,可以在html中添加如下配置

<style type="text/css">
        /*解决html转pdf文件中文不显示的问题*/
        body {
            font-family: SimSun;
        }

        /*设定纸张大小*/
        /* A4纸 */
        /* @page{size:210mm*297mm} */
        @page{size:a4}

        p {
            color: red;
        }
    </style>

到此结束在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值