POI word转html

maven配置

pom.xml
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/ooxml-schemas -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>ooxml-schemas</artifactId>
    <version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/fr.opensagres.xdocreport/xdocreport -->
<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>xdocreport</artifactId>
    <version>2.0.2</version>
</dependency>

异常 找不到org/apache/poi/POIXMLDocumentPart类

POIXMLDocumentPart已全版本更换放置的位置到org.apache.poi.ooxml包下,更新xdocreport至2.0.2
<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>xdocreport</artifactId>
    <version>2.0.2</version>
</dependency>

Java代码

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


import fr.opensagres.poi.xwpf.converter.core.*;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.commons.io.output.ByteArrayOutputStream;
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.usermodel.XWPFDocument;
import org.w3c.dom.Document;

/**
* @ClassName DocConvertHtmlUtil
* @Description: word 转 html 工具类
* @Author huapisong
* @Date 2020/3/24
* @Version V1.0
**/
public class DocConvertHtmlUtil {
    private final static String tempPath = "E:\\srv\\apps\\data\\";

    public static void main(String[] args) throws ParserConfigurationException, TransformerException, IOException {
        String sourceFilePath = "E:\\home\\testPdfObject\\JL20012000000128.docx";
        String sourceFilePathDoc = "E:\\home\\testPdfObject\\CG2020032400002782.doc";
        String filePath = "E:\\srv\\apps\\data\\doc.html";
//        doc2Html(sourceFilePathDoc, filePath);
//        docConvertHtml(sourceFilePath);

        docxConvertHtml(sourceFilePath);
    }

    /**
    * docx 转 html
    * @param sourceFilePath 
    */
    public static void docxConvertHtml(String sourceFilePath) {

        try {
            String outPutFile = "E:\\srv\\apps\\data\\";
            String htmlName = "docx.html";
            String fileOutName = outPutFile;
            long startTime = System.currentTimeMillis();
            XWPFDocument document = new XWPFDocument(new FileInputStream(sourceFilePath));

            XHTMLOptions options = XHTMLOptions.create();
//            options.URIResolver(new BasicURIResolver(outPutFile));
            // 导出图片
//            File imageFolder = new File(outPutFile);
//            options.setExtractor(new FileImageExtractor(imageFolder));
            // URI resolver
//            options.setIgnoreStylesIfUnused(false);
//            options.setFragment(true);
            // Extract image
            //  File imageFolder = new File( FileTools.getInstance().getRoot() + savePath);
            IImageExtractor extractor = new IImageExtractor() {
                private String savePath = "";

                public IImageExtractor setSavePath(String savePath) {
                    this.savePath = savePath;
                    return this;
                }

                @Override
                public void extract(String arg0, byte[] arg1) throws IOException {
                    byte[] bytev = arg1;
                    String fileName = arg0.substring(arg0.lastIndexOf("/") + 1);
                    FileTools.getInstance().saveFile(savePath, fileName, bytev);
                }
            }.setSavePath(outPutFile);
            options.setExtractor(extractor);
            options.URIResolver(new IURIResolver() {
                private String savePath = "";

                public IURIResolver init(String savePath) {
                    this.savePath = savePath;
                    return this;
                }

                @Override
                public String resolve(String arg0) {
                    String fileName = arg0.substring(arg0.lastIndexOf("/") + 1);
                    return savePath + fileName + ".html";
                }
            }.init(outPutFile));
            // 3) 将 XWPFDocument转换成XHTML
            OutputStream out = new FileOutputStream(new File(outPutFile + htmlName));
            XHTMLConverter.getInstance().convert(document, out, options);

            System.out.println("Generate " + fileOutName + " with " + (System.currentTimeMillis() - startTime) + " ms.");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
    * doc转换为html
    *
    * @param fileName
    * @param outPutFile
    * @throws TransformerException
    * @throws IOException
    * @throws ParserConfigurationException
    */
    public static void doc2Html(String fileName, String outPutFile) throws TransformerException, IOException, ParserConfigurationException {
        long startTime = System.currentTimeMillis();
        HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                return "test/" + suggestedName;
            }
        });
        wordToHtmlConverter.processDocument(wordDocument);
        // 保存图片
        List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
        if (pics != null) {
            for (int i = 0; i < pics.size(); i++) {
                Picture pic = (Picture) pics.get(i);
                System.out.println();
                try {
                    pic.writeImageContent(new FileOutputStream(tempPath + pic.suggestFullFileName()));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        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);
        out.close();
        writeFile(new String(out.toByteArray()), outPutFile);
        System.out.println("Generate " + outPutFile + " with " + (System.currentTimeMillis() - startTime) + " ms.");
    }

    /**
    * 写文件
    *
    * @param content
    * @param path
    */
    public static void writeFile(String content, String path) {
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try {
            File file = new File(path);
            fos = new FileOutputStream(file);
            bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
            bw.write(content);
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (bw != null)
                    bw.close();
                if (fos != null)
                    fos.close();
            } catch (IOException ie) {
            }
        }
    }

    /**
    * doc 转 html
    * @param sourceFilePath
    */
    public static void docConvertHtml(String sourceFilePath) {

        String filePath = "E:\\srv\\apps\\data\\";
        String htmlName = "doc.html";

        try {
            FileInputStream input = new FileInputStream(sourceFilePath);
            HWPFDocument wordDocument = new HWPFDocument(input);
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            //解析word文档
            wordToHtmlConverter.processDocument(wordDocument);
            Document htmlDocument = wordToHtmlConverter.getDocument();
            File htmlFile = new File(filePath + htmlName);
            OutputStream outStream = new FileOutputStream(htmlFile);
            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(outStream);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer serializer = factory.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    static class LocalFile{
        /**
        * 保存文件
        * @param fileName
        * @param foldPath
        * @param bins
        * @return
        */
        public static void saveFile(String foldPath,String fileName,byte[] bins){
            try {
                //data格式为:data:image/png;base64,iVBOR
                //以,分割
                StringBuilder filePath = new StringBuilder();
                filePath.append(foldPath).append(File.separatorChar).append(StringUtil.getUUID()).append(fileName);

                File localFile = new File(filePath.toString());
                FileOutputStream os = new FileOutputStream(localFile);
                os.write(bins);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private static class FileTools {
        public static LocalFile getInstance() {
            return null;
        }
    }
}