美文网首页
doc4j通过html生成doc

doc4j通过html生成doc

作者: 想揉娜娜奇的脸 | 来源:发表于2017-07-03 15:51 被阅读0次
    @RequestMapping(value = "/doc")
    public void doc(HttpServletRequest request, HttpServletResponse response, String wordname, String html) {
        try {
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
    
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((wordname + ".docx").getBytes("GBK"), "ISO-8859-1") + "");
            response.setContentType("application/msword");
            OutputStream stream = response.getOutputStream();
            MsWord.html2word(html, basePath).save(stream);
            stream.flush();
            stream.close();
        } catch (IOException | Docx4JException e) {
          e.printStackTrace();
        }
    }
    
    private WordprocessingMLPackage html2word(String html,String baseUrl) {
        Document doc = Jsoup.parse(html);
        doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml).escapeMode(Entities.EscapeMode.xhtml);
        WordprocessingMLPackage wordMLPackage = null;
        try {
            wordMLPackage = WordprocessingMLPackage.createPackage(PageSizePaper.valueOf("A4"), true);
            XHTMLImporterImpl xhtmlImporter = new XHTMLImporterImpl(wordMLPackage);
            wordMLPackage.getMainDocumentPart().getContent().addAll(xhtmlImporter.convert(doc.html(), baseUrl));
        } catch (Docx4JException e) {
            e.printStackTrace();
        }
        return wordMLPackage;
    }
    

    相关文章

      网友评论

          本文标题:doc4j通过html生成doc

          本文链接:https://www.haomeiwen.com/subject/uyfzcxtx.html