java将word内容转化成html

引入依赖

		<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi-xml</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- 针对2007以上版本的库 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!-- 针对2003版本的库 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId>
            <version>2.0.2</version>
        </dependency>

        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.12.0</version>
        </dependency>

OfficeConvertUtil 工具类

import cn.hutool.core.img.ImgUtil;
import fr.opensagres.poi.xwpf.converter.xhtml.Base64EmbedImgManager;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

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 java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class OfficeConvertUtil {



    /**
     * 将word2003转换为html文件

     * @throws IOException
     * @throws TransformerException
     * @throws ParserConfigurationException
     */
    public static String word2003ToHtml(HWPFDocument wordDocument) throws TransformerException,
            ParserConfigurationException {

        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .newDocument());
        wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> {
            BufferedImage bufferedImage = ImgUtil.toImage(content);
            String base64Img = ImgUtil.toBase64(bufferedImage, pictureType.getExtension());
            //  带图片的word,则将图片转为base64编码,保存在一个页面中
            StringBuilder sb = (new StringBuilder(base64Img.length() + "data:;base64,".length()).append("data:;base64,").append(base64Img));
            return sb.toString();
        });
        // 解析word文档
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outputStream);
        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);
        return outputStream.toString();
    }

    /**
     * 2007版本word转换成html
     *
     * @param document word文件路径
     * @return
     * @throws IOException
     */
    public static String word2007ToHtml(XWPFDocument document)
            throws IOException {
        //  带图片的word,则将图片转为base64编码,保存在一个页面中
        XHTMLOptions options = XHTMLOptions.create().indent(4).setImageManager(new Base64EmbedImgManager());
        // ) 将 XWPFDocument转换成XHTML
        // 生成html文件上级文件夹
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(document, outputStream, options);
        return outputStream.toString();
    }

}

输出内容

	    String content ;
         FileInputStream fis = new FileInputStream(file);
         if ( param.getPath().endsWith(".docx") ){
             XWPFDocument document = new XWPFDocument(fis);
             content = OfficeConvertUtil.word2007ToHtml(document);
             document.close();
         }else{
             HWPFDocument wordDocument = new HWPFDocument(fis);
             content = OfficeConvertUtil.word2003ToHtml(wordDocument);
             wordDocument.close();
         }
         // 关闭资源
         fis.close();
         content = content.replaceAll("\n","<br/>");
  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用Apache POI和JSoup库来实现将Word文档换为HTML脚本的功能。具体步骤如下: 1. 使用Apache POI库读取Word文档,得到文档内容。 2. 使用JSoup库创建HTML文档,并将Word文档内容逐一换为HTML标签。 3. 将生成的HTML文档保存到指定的文件中。 下面是一个简单的Java代码示例: ```java import java.io.*; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.WordToHtmlConverter; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; public class WordToHtmlConverterDemo { public static void main(String[] args) throws Exception { // 读取Word文档 FileInputStream fis = new FileInputStream("test.doc"); HWPFDocument document = new HWPFDocument(fis); // 创建HTML文档 Document htmlDocument = Jsoup.parse("<html><head><title></title></head><body></body></html>"); Element body = htmlDocument.body(); // 将Word文档内容换为HTML标签 WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(htmlDocument); wordToHtmlConverter.processDocument(document); Elements paragraphs = htmlDocument.select("p"); for (Element paragraph : paragraphs) { paragraph.tagName("div"); paragraph.attr("class", "paragraph"); } Elements tables = htmlDocument.select("table"); for (Element table : tables) { table.tagName("div"); table.attr("class", "table"); } // 将HTML文档保存到文件 FileWriter fileWriter = new FileWriter("test.html"); fileWriter.write(htmlDocument.outerHtml()); fileWriter.close(); } } ``` 注意:以上代码示例需要引入Apache POI和JSoup库。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

boymusic

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值