czt
2025-12-30 a206264f7baa07af1b48dfd45adc735e3ca2a963
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package com.fzzy.igds.utils;
 
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import com.fzzy.igds.data.ExportWordParam;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import org.springframework.http.MediaType;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * @Description 文档工具类,将数据源填充到模板并另存文件
 * @Author CZT
 * @Date 2025/4/21 16:14
 */
public class WordUtil {
 
    /**
     * 许可证字符串(可以放到resource下的xml文件中也可)
     */
    private static final String LICENSE = "<License>" +
            "<Data>" +
            "<Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products>" +
            "<EditionType>Enterprise</EditionType>" +
            "<SubscriptionExpiry>20991231</SubscriptionExpiry>" +
            "<LicenseExpiry>20991231</LicenseExpiry>" +
            "<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>" +
            "</Data>" +
            "<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>" +
            "</License>";
 
    /**
     * 将数据源填充到模板中并另存:主表+子表(可只有列表)
     *
     * @param param      数据源
     * @throws IOException
     */
    public static void exportWord(ExportWordParam param) throws Exception {
        //渲染模板
        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
        Configure config = null;
        ConfigureBuilder configureBuilder = Configure.newBuilder();
 
        if(StringUtils.isNotEmpty(param.getListName1())){
            configureBuilder.bind(param.getListName1(), policy);
        }
        if(StringUtils.isNotEmpty(param.getListName2())){
            configureBuilder.bind(param.getListName2(), policy);
        }
        if(StringUtils.isNotEmpty(param.getListName3())){
            configureBuilder.bind(param.getListName3(), policy);
        }
        if(StringUtils.isNotEmpty(param.getListName4())){
            configureBuilder.bind(param.getListName4(), policy);
        }
        if(StringUtils.isNotEmpty(param.getListName5())){
            configureBuilder.bind(param.getListName5(), policy);
        }
        config = configureBuilder.build();
        XWPFTemplate template = XWPFTemplate.compile(param.getTemplatePath() + param.getTemplateName(), config).render(param.getDataMap());
 
        //模板文件保存
        FileOutputStream fos = new FileOutputStream(param.getSavePath() +  param.getTemplateName());
        template.write(fos);
 
    }
 
    /**
     * 将数据源填充到模板中并另存:主表+子表(可只有列表)
     *
     * @param param      数据源
     * @throws IOException
     */
    public static void exportMoreWord(ExportWordParam param) throws Exception {
 
        Integer index = 900;
        List<String> wordList = new ArrayList<>();
        for (Map<String, Object> dataMap : param.getDataList()) {
            //渲染模板
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            Configure config = null;
            ConfigureBuilder configureBuilder = Configure.newBuilder();
 
            if(StringUtils.isNotEmpty(param.getListName1())){
                configureBuilder.bind(param.getListName1(), policy);
            }
            if(StringUtils.isNotEmpty(param.getListName2())){
                configureBuilder.bind(param.getListName2(), policy);
            }
            if(StringUtils.isNotEmpty(param.getListName3())){
                configureBuilder.bind(param.getListName3(), policy);
            }
            if(StringUtils.isNotEmpty(param.getListName4())){
                configureBuilder.bind(param.getListName4(), policy);
            }
            if(StringUtils.isNotEmpty(param.getListName5())){
                configureBuilder.bind(param.getListName5(), policy);
            }
            config = configureBuilder.build();
            XWPFTemplate template = XWPFTemplate.compile(param.getTemplatePath() + param.getTemplateName(), config).render(dataMap);
 
            wordList.add(param.getSavePath() + index + "-" + param.getTemplateName());
            //模板文件保存
            FileOutputStream fos = new FileOutputStream(param.getSavePath() + index + "-" + param.getTemplateName());
            template.write(fos);
            index ++;
        }
        //多个word合并
        mergeWord(wordList, param.getSavePath(), param.getTemplateName());
 
    }
 
    /**
     * 下载文档
     *
     * @param filePath 文档路径
     * @param fileName 文档名称
     * @param response
     * @throws Exception
     */
    public static void download(String filePath, String fileName, HttpServletResponse response) throws Exception {
 
        //下载
        if (!FileUtils.checkAllowDownload(fileName)) {
            throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
        }
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, fileName);
        FileUtils.writeBytes(filePath + fileName, response.getOutputStream());
    }
 
 
    /**
     * 设置 license 去除水印
     */
    private static void setLicense() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(LICENSE.getBytes());
        License license = new License();
        try {
            license.setLicense(byteArrayInputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * word 转 pdf 生成至指定路径,pdf为空则上传至word同级目录
     *
     * @param wordPath word文件路径
     * @param pdfPath  pdf文件路径
     */
    public static void wordConvertPdfFile(String wordPath, String pdfPath) {
        FileOutputStream fileOutputStream = null;
        try {
            setLicense();
            File file = new File(pdfPath);
            fileOutputStream = new FileOutputStream(file);
            Document doc = new Document(wordPath);
            doc.save(fileOutputStream, SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
 
        }
    }
 
    /**
     * 获取 生成的 pdf 文件路径,默认与源文件同一目录
     *
     * @param inputFilePath word文件
     * @return 生成的 pdf 文件
     */
    public static String getPdfName(String inputFilePath) {
        return inputFilePath.replaceAll("."+ getPostfix(inputFilePath), ".pdf");
    }
 
    public static String getPostfix(String inputFilePath) {
        return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
    }
 
    /*-------------多个word合并到成1个word文档----------*/
    public static void mergeWord(List<String> wordList, String mergeWordPath, String mergeWordName) {
        List<File> srcfile = new ArrayList<>();
        File file = null;
        for (String word : wordList) {
            file = new File(word);
            srcfile.add(file);
        }
 
        try {
            ArrayList<XWPFDocument> documentList = new ArrayList<>();
            for (int i = 0; i < srcfile.size(); i++) {
                FileInputStream in = new FileInputStream(srcfile.get(i).getPath());
                OPCPackage open = OPCPackage.open(in);
                XWPFDocument document = new XWPFDocument(open);
                documentList.add(document);
            }
            XWPFDocument doc = documentList.get(0);
            if (CollectionUtils.isEmpty(documentList)) {
                throw  new RuntimeException("待合并的word文档list为空");
            }
            int size = documentList.size();
            if (size > 1) {
                for (int i = 1; i < size; i++) {
                    // 从第二个word开始合并
                    XWPFDocument nextPageDoc = documentList.get(i);
                    // 最后一页不需要设置分页符,设置分页符后容易换页,可以去掉
                    if (i != (size-1)) {
                        nextPageDoc.createParagraph().setPageBreak(true);
                    }
                    appendBody(doc, nextPageDoc);
                }
            }
 
            new File(mergeWordPath + mergeWordName).delete();
            OutputStream dest = new FileOutputStream(mergeWordPath + mergeWordName);
            doc.write(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public void aqscMergeDoc(String outPutPath, String mergeWord) {
 
        List<File> srcfile = new ArrayList<>();
        File file1 = new File(outPutPath);
        File file2 = new File(mergeWord);
        srcfile.add(file1);
        srcfile.add(file2);
 
        try {
            ArrayList<XWPFDocument> documentList = new ArrayList<>();
            for (int i = 0; i < srcfile.size(); i++) {
                FileInputStream in = new FileInputStream(srcfile.get(i).getPath());
                OPCPackage open = OPCPackage.open(in);
                XWPFDocument document = new XWPFDocument(open);
                documentList.add(document);
            }
            XWPFDocument doc = documentList.get(0);
            if (CollectionUtils.isEmpty(documentList)) {
                throw  new RuntimeException("待合并的word文档list为空");
            }
            int size = documentList.size();
            if (size > 1) {
                doc.createParagraph().setPageBreak(true);
                for (int i = 1; i < size; i++) {
                    // 从第二个word开始合并
                    XWPFDocument nextPageDoc = documentList.get(i);
                    // 最后一页不需要设置分页符
                    if (i != (size-1)) {
                        nextPageDoc.createParagraph().setPageBreak(true);
                    }
                    appendBody(doc, nextPageDoc);
                }
            }
            new File(outPutPath).delete();
            OutputStream dest = new FileOutputStream(outPutPath);
            doc.write(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void appendBody(XWPFDocument src, XWPFDocument append) throws Exception {
        CTBody src1Body = src.getDocument().getBody();
        CTBody src2Body = append.getDocument().getBody();
        List<XWPFPictureData> allPictures = append.getAllPictures();
        // 记录图片合并前及合并后的ID
        Map<String, String> map = new HashMap<>();
        for (XWPFPictureData picture : allPictures) {
            String before = append.getRelationId(picture);
            // 将原文档中的图片加入到目标文档中
            String after = src.addPictureData(picture.getData(), org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_PNG);
            map.put(before, after);
        }
        appendBody(src1Body, src2Body, map);
    }
 
    private static void appendBody(CTBody src, CTBody append, Map<String, String> map) throws Exception {
        XmlOptions optionsOuter = new XmlOptions();
        optionsOuter.setSaveOuter();
        String appendString = append.xmlText(optionsOuter);
        String rgex = "<[\\s]*?w:sectPr[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?w:sectPr[\\s]*?>";
        appendString = appendString.replaceAll(rgex, "");
//        String srcString = src.xmlText();
        // 去除分页符
        String srcString = src.xmlText().replaceAll( "<w:p><w:r><w:br w:type=\"page\"/></w:r></w:p>", "" ).replaceAll( "<w:r><w:br w:type=\"page\"/></w:r>", "" );
        String prefix = srcString.substring(0, srcString.indexOf(">"));
        String mainPart = srcString.substring(srcString.indexOf(">"), srcString.lastIndexOf("<"));
        String sufix = srcString.substring(srcString.lastIndexOf("<"));
        String addPart = appendString.substring(appendString.indexOf(">"), appendString.lastIndexOf("<"));
        if (map != null && !map.isEmpty()) {
            // 对xml字符串中图片ID进行替换
            for (Map.Entry<String, String> set : map.entrySet()) {
                addPart = addPart.replace(set.getKey(), set.getValue());
            }
        }
        // 将两个文档的xml内容进行拼接
        CTBody makeBody = CTBody.Factory.parse(prefix + mainPart + addPart + sufix);
        src.set(makeBody);
    }
 
 
}