Docx4j导出latex公式到word(公式可编辑)

环境

核心代码

依赖项

docx4j:操作word文档(.docx)

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>6.0.1</version>
</dependency>
<!--下面这个jar好像不引入也没问题-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>

latex-word(第三方jar包):将latex值转成符合word xml标准的工具

github项目地址为:https://github.com/mao-yuwei/latex_word

相关文章为:https://blog.csdn.net/weixin_30633405/article/details/98518909

关键步骤

  1. 调用com.latextoword.Latex_Word.latexToWordAlreadyClean方法获取到latex对应的xml字符串,例如:

    1
    <m:oMath>......</m:oMath>
  2. 给根节点添加必要(非常重要,否则生成的文档将无法正常打开)的namespacexmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"

    1
    <m:oMath xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math">......</m:oMath>
  3. 调用org.docx4j.XmlUtils.unmarshalString方法将最终拼接好的xml字符串解析为Object

  4. 将转换好的对象add到word的元素对象中(诸如org.docx4j.wml.P)

  5. 最终效果如下

代码参考

https://github.com/surpass-wei/operating-office-demo/blob/master/src/main/java/com/surpass/word/WriteLaTeXFormula.java

注意事项

参考

https://blog.csdn.net/weixin_30633405/article/details/98518909
https://github.com/mao-yuwei/latex_word
https://github.com/plutext/docx4j/blob/master/docx4j-samples-docx4j/src/main/java/org/docx4j/samples/MathsEquationsFormulae.java