将百度富文本编辑器(ueditor)中的内容转化为word文档格式


业务场景

需求:根据富文本中的内容生成对应的word文档进行预览和下载功能。
实现: 采用 POIFSFileSystem 类相关实现,能够准确的将文字、格式相关内容转换成功,但是对于在线的网络图片,无法离线浏览或打开。因此最后采用Spire.doc中的工具进行转换(免费版本)。
官网网址:点击跳转

实现步骤

  1. 引入依赖
<dependency>
  <groupId>e-iceblue</groupId>
  <artifactId>spire.doc.free</artifactId>
  <version>2.7.3</version>
</dependency>
  1. 工具类,导出word
public static void exportWord(HttpServletRequest request, HttpServletResponse response, String content, String fileName) {

        try {
            //新建Document对象
            Document document = new Document();
            //添加section
            Section sec = document.addSection();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //添加段落并写入HTML文本
            sec.addParagraph().appendHTML(content);
            document.saveToStream(os,FileFormat.Docx);

            InputStream input = new ByteArrayInputStream(os.toByteArray());

            //输出文件
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");//导出word格式
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName, "utf-8") + ".docx");

            ServletOutputStream ostream = response.getOutputStream();
            int len =-1;
            byte []by = new byte[1024];
            while((len = input.read(by))!=-1) {
                ostream.write(by,0,len);
            }
            ostream.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

在线网络图片,在离线情况下也能够正常预览。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM