java Springboot富文本编辑器ueditor的内容使用itext5导出为pdf文件

本文讲解java在Springboot框架下使用百度的富文本编辑器ueditor,将富文本编辑器中的内容以html语言的形式保存到数据库中,然后从数据库中导出内容为pdf。

首先,在pom.xml包中引入itext5。

        <!-- 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 -->

关于百度的富文本编辑器的使用,本文不再讲解,只说在保存html文本到数据库中有一个坑。就是在将html语言导出为pdf文件时,默认的html语言的style一定要有关于字体的设置,否则,就只能导出数字和字母,但不能导出汉字。但富文本编辑器默认输出时,是不带style的字体的。因此,在写导出函数时,一定要加上style,说明在默认情况下的style字体。这一点一定要注意,下文将贴上代码。

在Service层Impl中写导出pdf的函数,

    public void exportPDF(HttpServletRequest request, HttpServletResponse response, String title, String text) {
        Document document = new Document();

        try {
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    new String( (title + ".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;\"><span style=\"font-family: 黑体, SimHei; font-size: 24px;\">"
                    + title + "</span></p>" + text + "</body></html>";
            byte b[] = content.getBytes("utf-8");  //这里是必须要设置编码的,不然导出中文就会乱码。
            ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中

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

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

上述代码,title表示标题,text表示文本,如果你的文章代码和标题都在富文本编辑器导出的html语言里,那你用一个就好。

这样,在controller层中调用函数,即可实现pdf的导出,亲测有效。

猜你喜欢

转载自blog.csdn.net/weixin_42259631/article/details/80994935