【JAVA】docx4j word(docx)转html

引入依赖pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>wordUtil</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <revision>8.3.0</revision>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.26</version>
        </dependency>
        <dependency>
            <groupId>org.docx4j</groupId>
            <artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
            <version>${revision}</version>
        </dependency>
         <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.3</version>
        </dependency>
    </dependencies>

</project>

实现代码

import org.docx4j.Docx4J;
import org.docx4j.convert.out.HTMLSettings;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Entities;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dengqianghua
 * @description: docx导出html
 * @date 2021/6/30 16:16
 */
public class WordUtil {
    public static void main(String[] args) throws Exception {
        String filePath = "/var/2.docx";
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(filePath));
        OutputStream os = new ByteArrayOutputStream();
        HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
        htmlSettings.setUserBodyTail("");
        htmlSettings.setUserBodyTop("");
        htmlSettings.setOpcPackage(wordMLPackage);
        Docx4J.toHTML(htmlSettings, os, Docx4J.FLAG_NONE);
        String content = os.toString();
        //默认样式替换
        int start = content.indexOf("<style><!--");
        int end = content.indexOf("--></style>");
        Map<String, String> replaceMap = getReplaceContent();
        if (start > 0 && end > 0) {
            replaceMap.put(content.substring(start + 7, end + 3), replaceMap.get("style"));
        }
        replaceMap.remove("style");

        for (Map.Entry<String, String> item : replaceMap.entrySet()) {
            content = content.replace(item.getKey(), item.getValue());
        }
        new FileOutputStream("/var/1.html").write(htmlToXhtml(content).getBytes(StandardCharsets.UTF_8));

    }

    /**
     * html转xhtml不然导出会存在问题
     * @param html
     * @return
     */
    public static String htmlToXhtml(String html) {
        org.jsoup.nodes.Document doc = Jsoup.parse(html);
        doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml).escapeMode(Entities.EscapeMode.xhtml);
        return doc.html();
    }

    /**
     * 替换的内容
     * @return
     */
    static Map<String, String> getReplaceContent() {
        Map<String, String> replaceMap = new HashMap<>();
        replaceMap.put("style", "html, body, div, span, h1, h2, h3, h4, h5, h6, p, a, img,  table, caption, tbody, tfoot, thead, tr, th, td " +
                "{ margin: 0; padding: 0; border: 0;}" +
                "body {line-height: 1.5;} ");

        replaceMap.put("TO HIDE THESE MESSAGES, TURN OFF debug level logging for org.docx4j.convert.out.common.writer.AbstractMessageWriter", "");
        replaceMap.put("<script type=\"text/javascript\"><!--function toggleDiv(divid){if(document.getElementById(divid).style.display == 'none'){document.getElementById(divid).style.display = 'block';}else{document.getElementById(divid).style.display = 'none';}}\n" +
                "--></script>", "");
        return replaceMap;
    }


}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
Docx4j是一个用于处理Word文档的Java库,它提供了丰富的功能,包括创建、修改和Word文档等。要将Word文档换为PDF,可以使用Docx4j提供的功能。 首先,你需要在项目中引入Docx4j库的依赖。你可以在Maven或Gradle中添加以下依赖: Maven: ```xml <dependency> <groupId>org.docx4j</groupId> <artifactId>docx4j</artifactId> <version>8.2.9</version> </dependency> ``` Gradle: ```groovy implementation 'org.docx4j:docx4j:8.2.9' ``` 接下来,你可以使用以下代码将Word文档换为PDF: ```java import org.docx4j.Docx4J; import org.docx4j.convert.out.FOSettings; public class WordToPdfConverter { public static void main(String[] args) throws Exception { // 加载Word文档 String inputFilePath = "path/to/input.docx"; org.docx4j.openpackaging.packages.WordprocessingMLPackage wordMLPackage = Docx4J.load(new java.io.File(inputFilePath)); // 创建FOSettings对象,并设置输出格式为PDF FOSettings foSettings = Docx4J.createFOSettings(); foSettings.setWmlPackage(wordMLPackage); foSettings.setApacheFopMime("application/pdf"); // 设置输出路径 String outputFilePath = "path/to/output.pdf"; java.io.OutputStream outputStream = new java.io.FileOutputStream(outputFilePath); // 执行Docx4J.toFO(foSettings, outputStream, Docx4J.FLAG_EXPORT_PREFER_XSL); // 关闭输出流 outputStream.close(); System.out.println("Word文档换为PDF成功!"); } } ``` 以上代码中,你需要将`inputFilePath`替换为要换的Word文档的路径,将`outputFilePath`替换为要保存的PDF文件的路径。执行代码后,将会生成对应的PDF文件。 希望以上信息对你有所帮助!如果你有任何其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

天空~华

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

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

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

打赏作者

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

抵扣说明:

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

余额充值