【word | html】word(doc | docx) 转 html

1. 需求                

上传 word 之后 ,有时候会需要预览 上传的 word ,这个时候可以把 word 转为 html 然后在页面显示


2.测试 jar 包            

gradle 依赖 (文件处理相关 jar 包)


    compile group: 'org.apache.poi', name: 'poi', version: '3.13'//word excel 解析
    compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.13'//word excel 解析
    compile group: 'org.apache.poi', name: 'poi-scratchpad', version: '3.13'//word excel 解析
    compile group: 'fr.opensagres.xdocreport', name: 'org.apache.poi.xwpf.converter.xhtml', version: '1.0.6'//docx 解析为 html
    compile group: 'org.jsoup', name: 'jsoup', version: '1.10.1'//html 解析

3. 代码案例                  

 util 类

package com.ycit.utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.springframework.util.CollectionUtils;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by xlch on 2017/1/11.
 */
public class POIUtils {

    public static String docToHtml(HWPFDocument document, String path) throws Exception {
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            @Override
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                return suggestedName;
            }
        });
        wordToHtmlConverter.processDocument(document);
        List<Picture> pictures = document.getPicturesTable().getAllPictures();
        if (!CollectionUtils.isEmpty(pictures)) {
            for (Picture picture:pictures) {
                picture.writeImageContent(new FileOutputStream(path + picture.suggestFullFileName()));
            }
        }
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outStream);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        outStream.close();
        return new String(outStream.toByteArray(), "utf-8");
    }

    /**
     * 处理表格会有点问题
     * @param document
     * @param path
     * @return
     * @throws IOException
     */
    public static String docXToHtml(XWPFDocument document, String path)throws IOException {
        XHTMLOptions options = XHTMLOptions.create();
        options.setIgnoreStylesIfUnused(false);
        options.setFragment(true);
        options.setExtractor(new FileImageExtractor(new File(path)));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(document, out, options);
        String content = new String(out.toByteArray());
        org.jsoup.nodes.Document document1 = Jsoup.parse(content);
        return document1.html();
    }
}


若保存为 html 文件 则

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

该为

OutputStream outputStream = new FileOutputStream(new File("你的存储路径"));



测试类:

package com.ycit.poi;

import com.ycit.utils.POIUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;

/**
 * Created by xlch on 2016/12/30.
 */
public class WordToHtml {

    @Test
    public void wordToHtml() throws Exception {
        String path = "D:\\about project\\perp-service\\5812-1.doc";
//        String path = "D:\\about project\\perp-service\\11.docx";
        File file = new File(path);
        String content;
        String paths = "D:\\about project\\perp-service\\";
        FileInputStream in = new FileInputStream(file);
        if (".docx".equals(path.substring(path.lastIndexOf(".", path.length())))) {
            XWPFDocument document = new XWPFDocument(in);
            content = POIUtils.docXToHtml(document,paths);
        } else if (".doc".equals(path.substring(path.lastIndexOf(".", path.length())))) {
            HWPFDocument document = new HWPFDocument(in);
            content = POIUtils.docToHtml(document,paths);
        } else {
            throw new RuntimeException("文件格式不正确");
        }
        System.out.println(content);
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值