springboot 富文本 导出word 、pdf

1.导出word

添加依赖

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>

实现层代码

private void downloadWord(HttpServletResponse response, Resource resource) {
        String title = resource.getTitle();
        String text = resource.getContent();
        try {
            //word内容
            String content="<html><body>" +
                    "<p style=\"text-align: center;\"><span style=\"font-family: 黑体, SimHei; font-size: 24px;\">"
                    + title + "</span></p>" + text + "</body></html>";
            byte b[] = content.getBytes("GBK");  //这里是必须要设置编码的,不然导出中文就会乱码。
            ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中

            /*
             * 关键地方
             * 生成word格式 */
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
            //输出文件
//            request.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");//导出word格式
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    new String(title.getBytes("GB2312"),"iso8859-1") + ".doc");
            ServletOutputStream ostream = response.getOutputStream();
            poifs.writeFilesystem(ostream);
            bais.close();
            ostream.close();
            poifs.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

2.导出pdf

添加依赖

<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</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.8</version>
        </dependency>

压缩并导出实现代码

private void downloadPdf(HttpServletResponse response, Resource resource) {
        String content = resource.getContent();
        content = MyUtil.handleConvertPdfContent(content);
        String rootDir = System.getProperty("user.dir")+"/";
        String pdfDir = rootDir+"temp/pdf/";
        String pdfFileName = resource.getTitle()+".pdf";
        try {
            String path = pdfDir + pdfFileName;
            File pdfFileDir = new File(pdfDir);
            if (!pdfFileDir.exists()) {
                pdfFileDir.mkdirs();
            }

            FileOutputStream pdfOut = new FileOutputStream(path);

            // 第一步 创建文档实例 文章pdf导出+压缩包下载
            Document document = new Document();
            // 第二步 获取PdfWriter实例 写入文件到目录 pdfDir + responseFileName
            PdfWriter writer = PdfWriter.getInstance(document, pdfOut);
            // 第三步 打开文档
            document.open();
            //获取 XMLWorkerHelper实例
            XMLWorkerHelper work = XMLWorkerHelper.getInstance();
            //解析html文件,创建pdf文档
            work.parseXHtml(writer, document, new ByteArrayInputStream(content.getBytes()));
            // 第五部 操作完成后必须执行文档关闭操作。
            document.close();
            writer.close();
            pdfOut.close();

            // 压缩pdf文件
            String zipDir = rootDir + "temp/zip/";
            String zipPath = zipDir + resource.getTitle() + ".zip";
            File zipFile = new File(zipPath);
            File pdfFile1 = new File(path);
            ZipUtil.zip(zipFile, false, pdfFile1);

            // 将zip file写入response流
            //设置response内容
            String zipFileName = resource.getTitle() + ".zip";
            // 这里中文名字导致了下载报错 暂不解决
            String responseFileName = new String("download.zip".getBytes(), "utf-8");
            response.reset(); // 非常重要
            ServletOutputStream responseOutputStream = response.getOutputStream();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + responseFileName);
            InputStream in = new FileInputStream(zipPath);
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) > 0) {
                responseOutputStream.write(buffer, 0, len);
            }
            in.close();
            responseOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtil.delAllFile(rootDir + "/temp");
        }
    }

 

posted @ 2021-03-30 14:19  官萧何  阅读(2517)  评论(0编辑  收藏  举报