Java将编辑器内容生成pdf文件下载

添加依赖

<!-- itext5 start -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.10</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.11</version>
        </dependency>
        <!-- itext5 end -->
 @GetMapping("/exportPDF")
    public void exportPDF(HttpServletRequest request, HttpServletResponse response) {
        Document document = new Document();

        try {
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    new String( ("文件123" + ".pdf").getBytes(),  "iso-8859-1"));
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            document.open();
            //在下面,body中设置了style,设置了默认字体为宋体,这样导出时的html语言就默认带有了字体,汉字才会导出成功
            String content="<html><body style=\"font-family: 宋体, SimHei;\">" +
                    "<p style=\"text-align: center;\">"
                   + "</p><p style=\"text-align: center;\"><span style=\"font-size: 36px;\"><strong><span style=\"color: rgb(255, 0, 0); text-decoration: underline;\">乐清市大数据管理中心</span></strong></span></p><p style=\"text-align: center;\"><span style=\"color: rgb(0, 0, 0); text-decoration: none; font-size: 24px;\">乐清市XXX项目方案论证意见</span></p><p>&nbsp; 2022年xx月xx日,乐清市人民政府办公室(大数据管理中心)会同财政局、教育局等部门,组织专家在乐清市行政管理中心主楼5楼2号会议室,召开了“乐清市东山小学智能化工程项目”(以下简称项目)方案评审会,专家组听取了项目建设单位的介绍,审阅了有关资料,并进行了质询。经讨论,形成论证意见如下:</p><p><br/></p><p>&nbsp; 专家签名:<br/></p></body></html>";
            byte b[] = content.getBytes("utf-8");  //这里是必须要设置编码的,不然导出中文就会乱码。
            ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中

            XMLWorkerHelper.getInstance().parseXHtml(writer, document, bais, Charset.forName("UTF-8"));

            bais.close();
            document.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

 

posted @ 2022-08-04 19:12  码奴生来只知道前进~  阅读(10)  评论(0)    收藏  举报