Aspose.word Java实现html转word,word转html

实现代码如下:

/**
     * html字节数组转word字节数组
     * @Title: htmlToWordTest
     * @Description: html字节数组转word字节数组
     * @param content html字节数组
     * @param toType 值为SaveFormat.DOCX或SavaFormat.Doc对应的值
     * @return: byte
     */
    public static byte[] htmlToWord(byte[] content, Integer toType) {
          
   
        byte[] result = new byte[1];
        try {
          
   
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            InputStream is = new ByteArrayInputStream(content);
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            InputStreamReader streamReader = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader reader = new BufferedReader(streamReader);
            String line;
            StringBuilder html = new StringBuilder();
            while ((line = reader.readLine()) != null) {
          
   
                html.append(line);
            }
            reader.close();
            builder.insertHtml(String.valueOf(html));
            doc.save(os, toType);
            log.info("html转word成功!");
            result = os.toByteArray();
        } catch (Exception e) {
          
   
            log.error("html转word失败!", e);
        }
        return result;
    }

    /**
     * word字节数组转html字节数组
     * @Title: wordToHtml
     * @Description: word字节数组转html字节数组
     * @param content doc、docx字节数组
     * @return: byte
     */
    public static byte[] wordToHtml(byte[] content) {
          
   
        byte[] result = new byte[1] ;
        try {
          
   
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            InputStream sbs = new ByteArrayInputStream(content);
            Document document = new Document(sbs);
            HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.HTML);
            options.setExportImagesAsBase64(true);
            document.save(os, options);
            log.info("html转word成功!");
            result = os.toByteArray();
        } catch (Exception e) {
          
   
            log.error("word转html失败!", e);
        }
        return result;
    }
经验分享 程序员 微信小程序 职场和发展