將百度富文本編輯器(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