|
|
@@ -0,0 +1,54 @@
|
|
|
+package com.github.jfcloud.gene.config;
|
|
|
+
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.docx4j.Docx4jProperties;
|
|
|
+import org.docx4j.jaxb.BinderListenerUtils;
|
|
|
+import org.docx4j.jaxb.Context;
|
|
|
+import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
|
|
|
+import org.springframework.boot.ApplicationArguments;
|
|
|
+import org.springframework.boot.ApplicationRunner;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import javax.xml.bind.JAXBException;
|
|
|
+import java.io.InputStream;
|
|
|
+import java.io.OutputStream;
|
|
|
+
|
|
|
+@Slf4j
|
|
|
+@Component
|
|
|
+public class Docx4jHelper implements ApplicationRunner {
|
|
|
+
|
|
|
+ private static final WordprocessingMLPackage.FilterSettings settings = new WordprocessingMLPackage.FilterSettings();
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void run(ApplicationArguments args) {
|
|
|
+ //初始化Context和Docx4jProperties,加速文档转换
|
|
|
+ log.info("初始化Docx4j:{}", Context.jcXmlPackage.toString());
|
|
|
+ Docx4jProperties.getProperty("docx4j");
|
|
|
+
|
|
|
+ try {
|
|
|
+ //初始化binderListener
|
|
|
+ BinderListenerUtils.getBinderListener();
|
|
|
+ } catch (JAXBException ignore) {
|
|
|
+ }
|
|
|
+
|
|
|
+ //规范docx语法
|
|
|
+ settings.setTidyForDocx4all(true);
|
|
|
+ log.info("初始化Docx4j完成");
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 转换docx
|
|
|
+ */
|
|
|
+ public static void convert(InputStream in, OutputStream out) throws Exception {
|
|
|
+ load(in).save(out);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 加载docx
|
|
|
+ */
|
|
|
+ public static WordprocessingMLPackage load(InputStream in) throws Exception {
|
|
|
+ WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(in);
|
|
|
+ wordMLPackage.filter(settings);
|
|
|
+ return wordMLPackage;
|
|
|
+ }
|
|
|
+}
|