“mitao”
2026-05-16 881332a25bcbbe3bebb696f6d0728fba559ef635
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
327
328
329
330
331
332
333
334
335
336
package com.estate.expert.admin.utils.wordtopdf;
 
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
@Slf4j
@Component
public class WordUtil {
 
    /**
     * 基于模板生成 Word 文档
     *
     * @param basePackagePath  resources 目录下模板所在包路径
     * @param templateFileName 模板文件名
     * @param templateParam    模板参数
     * @param fileName         文件名
     */
    @Resource
    private PdfUtils pdfUtils;
    public static void fillTemplate(String templatePath, String outputPath,Map<String, Object> dataMap) {
        try (FileInputStream fis = new FileInputStream(templatePath)) {
            // 设置默认编码为UTF-8
            System.setProperty("file.encoding", "UTF-8");
 
            XWPFDocument document = new XWPFDocument(fis);
            XWPFParagraph pic = document.createParagraph();
            Base64.Decoder decoder = Base64.getDecoder();
            // 处理段落
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                replaceParagraph(paragraph, dataMap);
            }
 
            // 处理表格
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            replaceParagraph(paragraph, dataMap);
                        }
                    }
                }
            }
 
            // 使用UTF-8编码保存文件
            try (FileOutputStream fos = new FileOutputStream(outputPath)) {
                document.write(fos);
            }
 
            System.err.println("模板填充完成!文件保存在: " + outputPath);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    private static void replaceParagraph(XWPFParagraph paragraph, Map<String, Object> dataMap) {
        // 获取段落中所有runs
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs == null || runs.isEmpty()) return;
 
        // 首先合并所有runs的文本,以便正确识别占位符
        StringBuilder fullText = new StringBuilder();
        for (XWPFRun run : runs) {
            String text = run.getText(0);
            if (text != null) {
                fullText.append(text);
            }
        }
 
        String paragraphText = fullText.toString();
 
        // 使用正则表达式查找所有占位符,包括括号内的
        Pattern pattern = Pattern.compile("\\$\\{[^}]+\\}|\\([^)]*\\$\\{[^}]+\\}[^)]*\\)");
        Matcher matcher = pattern.matcher(paragraphText);
 
        List<ReplacementInfo> replacements = new ArrayList<>();
 
        // 收集所有需要替换的信息
        while (matcher.find()) {
            String matched = matcher.group();
            int start = matcher.start();
            int end = matcher.end();
 
            // 找出涉及到的runs
            int startRun = -1;
            int endRun = -1;
            int currentPos = 0;
 
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                String runText = run.getText(0);
                if (runText == null) continue;
 
                int runLength = runText.length();
                if (startRun == -1 && currentPos + runLength > start) {
                    startRun = i;
                }
                if (currentPos + runLength >= end) {
                    endRun = i;
                    break;
                }
                currentPos += runLength;
            }
 
            if (startRun != -1 && endRun != -1) {
                // 处理括号内的占位符
                String replacement = processPlaceholder(matched, dataMap);
                replacements.add(new ReplacementInfo(startRun, endRun, matched, replacement));
            }
        }
 
        // 从后向前替换,避免位置变化影响
        Collections.sort(replacements, (a, b) -> b.startRun - a.startRun);
 
        for (ReplacementInfo info : replacements) {
            replaceRunRange(paragraph, info);
        }
    }
 
    private static String processPlaceholder(String text, Map<String, Object> dataMap) {
        // 处理括号内的占位符
        Pattern placeholderPattern = Pattern.compile("\\$\\{([^}]+)\\}");
        Matcher matcher = placeholderPattern.matcher(text);
 
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String placeholder = matcher.group(0); // 完整的占位符
            String key = matcher.group(1); // 占位符中的键
            String replacement = Objects.nonNull(dataMap.get("${" + key + "}"))?String.valueOf(dataMap.get("${" + key + "}")):"";
 
            if (replacement != null) {
                // 如果在括号内,保留括号
                if (text.startsWith("(") && text.endsWith(")")) {
                    matcher.appendReplacement(result, replacement);
                } else {
                    matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
                }
            }
        }
        matcher.appendTail(result);
 
        return result.toString();
    }
 
    private static void replaceRunRange(XWPFParagraph paragraph, ReplacementInfo info) {
        List<XWPFRun> runs = paragraph.getRuns();
 
        // 保存第一个run的样式
        XWPFRun styleRun = runs.get(info.startRun);
        RunStyle style = new RunStyle(styleRun);
 
        // 删除范围内的所有runs
        for (int i = info.endRun; i >= info.startRun; i--) {
            paragraph.removeRun(i);
        }
 
        // 创建新的run并设置文本
        XWPFRun newRun = paragraph.insertNewRun(info.startRun);
        // 如果有回车符,则插入一个空行
        if (info.replacementText.contains("\n") || info.replacementText.contains("\r") || info.replacementText.contains("\r\n")) {
            log.info("info.originalText=================: {}", info.replacementText);
            // 每一个\n,\r,\r\n都插入一个空行,并且最后的文本进行换行,为一整个文本
            String[] s = info.replacementText.split("\r\n");
            for (int i = 0; i < s.length; i++) {
                if (i == 0) {
                    newRun.setText(s[i] + "       ");
                }else {
//                    newRun.addCarriageReturn();
                    newRun.setText(s[i] + "       ");
                }
            }
        }else {
            newRun.setText(info.replacementText);
        }
 
        // 应用样式
        style.applyStyle(newRun);
    }
 
 
    /**
     * 生成PDF文件
     * @param basePackagePath 模板文件所在的包路径
     * @param templateFileName 模板文件名
     * @param templateParam 模板参数
     * @param fileName  填充参数后的word文件名
     * @param saveDirectory 填充参数后的word保存文件目录
     * @return
     */
    public String generatePdf(String basePackagePath, String templateFileName, Map<String,Object> templateParam, String fileName, String saveDirectory) {
        try {
            fillTemplate(basePackagePath+templateFileName, saveDirectory+fileName+".docx", templateParam);
            String filePath = saveDirectory + fileName + ".docx";
            File file = new File(filePath);
 
            // 检查文件是否存在
            if (!file.exists()) {
                throw new FileNotFoundException("文件不存在: " + filePath);
            }
 
            // 读取文件内容
            byte[] fileContent = new byte[(int) file.length()];
            try (FileInputStream fis = new FileInputStream(file)) {
                fis.read(fileContent);
            }
 
            String test = pdfUtils.test(fileName + ".docx");
//            MultipartFile mockMultipartFile = new MockMultipartFile(encodedFileName+".doc", fileContent);
//            String s = ObsUploadUtil.obsUpload(mockMultipartFile);
            return test;
        } catch (IOException e) {
            log.error("生成pdf异常,异常原因:{}", e.getMessage(), e);
            throw new RuntimeException("生成pdf异常,异常原因:" + e.getMessage());
        }
    }
 
    private static class ReplacementInfo {
        int startRun;
        int endRun;
        String originalText;
        String replacementText;
 
        ReplacementInfo(int startRun, int endRun, String originalText, String replacementText) {
            this.startRun = startRun;
            this.endRun = endRun;
            this.originalText = originalText;
            this.replacementText = replacementText;
        }
    }
 
    // 用于保存和恢复运行样式的辅助类
    private static class RunStyle {
        String fontFamily;
        int fontSize;
        boolean bold;
        boolean italic;
        String color;
        UnderlinePatterns underline;
 
        RunStyle(XWPFRun run) {
            this.fontFamily = run.getFontFamily();
            this.fontSize = run.getFontSize();
            this.bold = run.isBold();
            this.italic = run.isItalic();
            this.color = run.getColor();
            this.underline = run.getUnderline();
        }
 
        void applyStyle(XWPFRun run) {
            if (fontFamily != null) {
                run.setFontFamily(fontFamily);
                run.setFontFamily(fontFamily, XWPFRun.FontCharRange.eastAsia);
            }
            if (fontSize != -1) {
                run.setFontSize(fontSize);
            }
            run.setBold(bold);
            run.setItalic(italic);
            if (color != null) {
                run.setColor(color);
            }
            if (underline != null) {
                run.setUnderline(underline);
            }
        }
    }
 
//    public String generatePdf(String basePackagePath, String templateFileName, Object templateParam, String fileName, String saveDirectory) {
//        try {
//            // 创建 Freemarker 的 Configuration 对象,设置默认的不兼容改进选项
//            Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
//            configuration.setDefaultEncoding("utf-8");
//            // 设置模板加载器,加载模板文件
//            configuration.setTemplateLoader(new ClassTemplateLoader(getClass(), basePackagePath));
//            Template t = configuration.getTemplate(templateFileName, "utf-8");
//
//            // 使用 URLEncoder 对文件名进行编码,以防止中文文件名在不同浏览器和操作系统下出现乱码问题
////            String encodedFileName = URLEncoder.encode(fileName + "_" + System.currentTimeMillis(), "utf-8");
//            String encodedFileName =fileName ;
//
//            // 定义保存文件的路径
//            File saveDir = new File(saveDirectory);
//            if (!saveDir.exists()) {
//                saveDir.mkdirs();
//            }
//
//            // 定义文件名
//            String filePath = saveDir.getAbsolutePath() + File.separator + encodedFileName + ".doc";
//
//            // 创建 Writer 对象,用于将生成的文档写到文件中,缓存区大小设为 10KB
//            Writer out = new BufferedWriter(new FileWriter(filePath), 10240);
//
//            // 将模型数据与模板结合生成 Word 文档,写入到 Writer 对象中
//            t.process(templateParam, out);
//            out.close();
//
//            File file = new File(filePath);
//
//            // 检查文件是否存在
//            if (!file.exists()) {
//                throw new FileNotFoundException("文件不存在: " + filePath);
//            }
//
//            // 读取文件内容
//            byte[] fileContent = new byte[(int) file.length()];
//            try (FileInputStream fis = new FileInputStream(file)) {
//                fis.read(fileContent);
//            }
//
//            String test = pdfUtils.test(encodedFileName + ".doc");
////            MultipartFile mockMultipartFile = new MockMultipartFile(encodedFileName+".doc", fileContent);
////            String s = ObsUploadUtil.obsUpload(mockMultipartFile);
//            return test;
//        } catch (IOException | TemplateException e) {
//            log.error("生成pdf异常,异常原因:{}", e.getMessage(), e);
//            throw new RuntimeException("生成pdf异常,异常原因:" + e.getMessage());
//        }
//    }
 
 
 
 
}