From 135cc18c4ef8ab301a6ea93042fcc2a2fb8e8436 Mon Sep 17 00:00:00 2001 From: aipper Date: Mon, 27 Oct 2025 13:47:03 +0800 Subject: [PATCH] todo --- .../strategy/common/FileNameComparator.java | 51 ++ .../point/strategy/common/OfdToPdfUtil.java | 9 +- .../point/strategy/common/PdfFileHelper.java | 186 ++++- .../strategy/service/FileManageService.java | 742 +++++++----------- .../ureport/service/UreportService.java | 1 + 5 files changed, 514 insertions(+), 475 deletions(-) create mode 100644 src/main/java/com/point/strategy/common/FileNameComparator.java diff --git a/src/main/java/com/point/strategy/common/FileNameComparator.java b/src/main/java/com/point/strategy/common/FileNameComparator.java new file mode 100644 index 0000000..5d1d23c --- /dev/null +++ b/src/main/java/com/point/strategy/common/FileNameComparator.java @@ -0,0 +1,51 @@ +package com.point.strategy.common; + +import java.io.File; +import java.util.Comparator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class FileNameComparator implements Comparator { + + private static final Pattern NUMBER_PATTERN = Pattern.compile("(\\d+)"); + + @Override + public int compare(String s1, String s2) { + String name1 = new File(s1).getName(); + String name2 = new File(s2).getName(); + + Matcher m1 = NUMBER_PATTERN.matcher(name1); + Matcher m2 = NUMBER_PATTERN.matcher(name2); + + int pos1 = 0, pos2 = 0; + + while (m1.find() && m2.find()) { + // 比较数字前的字符串部分 + String prefix1 = name1.substring(pos1, m1.start()); + String prefix2 = name2.substring(pos2, m2.start()); + + int prefixCompare = prefix1.compareTo(prefix2); + if (prefixCompare != 0) { + return prefixCompare; + } + + // 比较数字部分(按数值比较) + Long num1 = Long.parseLong(m1.group()); + Long num2 = Long.parseLong(m2.group()); + + int numCompare = num1.compareTo(num2); + if (numCompare != 0) { + return numCompare; + } + + pos1 = m1.end(); + pos2 = m2.end(); + } + + // 比较剩余部分 + String suffix1 = name1.substring(pos1); + String suffix2 = name2.substring(pos2); + + return suffix1.compareTo(suffix2); + } +} diff --git a/src/main/java/com/point/strategy/common/OfdToPdfUtil.java b/src/main/java/com/point/strategy/common/OfdToPdfUtil.java index 2faaca1..6846fa5 100644 --- a/src/main/java/com/point/strategy/common/OfdToPdfUtil.java +++ b/src/main/java/com/point/strategy/common/OfdToPdfUtil.java @@ -1,5 +1,6 @@ package com.point.strategy.common; +import org.ofdrw.converter.ConvertHelper; import org.ofdrw.converter.export.PDFExporterPDFBox; import java.nio.file.Paths; @@ -16,12 +17,10 @@ public class OfdToPdfUtil { public static void ofdToPdf(String resourceFilePath, String targetFilePath){ try { // 按照OFD导出器的标准模式使用 - PDFExporterPDFBox exporter = new PDFExporterPDFBox( - Paths.get(resourceFilePath), - Paths.get(targetFilePath) + ConvertHelper.toPdf( + Paths.get(resourceFilePath), + Paths.get(targetFilePath) ); - exporter.export(); - exporter.close(); } catch (Exception e) { throw new RuntimeException("OFD转PDF失败: " + e.getMessage(), e); } diff --git a/src/main/java/com/point/strategy/common/PdfFileHelper.java b/src/main/java/com/point/strategy/common/PdfFileHelper.java index 210cff0..710a0b2 100644 --- a/src/main/java/com/point/strategy/common/PdfFileHelper.java +++ b/src/main/java/com/point/strategy/common/PdfFileHelper.java @@ -20,9 +20,11 @@ import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; -import java.util.Arrays; -import java.util.Date; -import java.util.Iterator; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.List; @Slf4j public class PdfFileHelper { @@ -390,7 +392,17 @@ public class PdfFileHelper { return false; } } - Arrays.sort(fileArray); + // 按文件名中的数字片段正序排序(如 xxx.001.pdf, xxx.002.pdf) + try { + log.info("mergePdf 接收到 {} 个PDF,按文件名数字片段正序合并。", (fileArray == null ? 0 : fileArray.length)); + if (fileArray != null) { + Arrays.sort(fileArray, new FileNameComparator()); + for (int idx = 0; idx < fileArray.length; idx++) { + log.info("排序后合并顺序 {} -> {}", idx + 1, fileArray[idx]); + } + } + } catch (Exception ignore) { + } Document document = null; PdfCopy pdfCopy = null; try { @@ -768,6 +780,172 @@ public class PdfFileHelper { mergePdf(fileArray, tarFile); } + public static boolean mergeOfdAndPdf(String[] sourceFiles, String targetFile, String tempDir) { + if (sourceFiles == null || sourceFiles.length == 0) { + log.warn("输入文件数组为空"); + return true; + } + Path tempPath = Paths.get(tempDir); + try { + if (!Files.exists(tempPath)) { + Files.createDirectories(tempPath); + } + } catch (Exception e) { + log.error("创建临时目录失败: {}", tempDir, e); + return false; + } + List pdfFiles = new ArrayList<>(); + List tempFilesToDelete = new ArrayList<>(); + + try { + // 不在此处改变顺序,保持调用方传入顺序(调用方如需排序,请在外部完成) + try { + log.info("mergeOfdAndPdf 接收到 {} 个源文件(保持传入顺序)", (sourceFiles == null ? 0 : sourceFiles.length)); + if (sourceFiles != null) { + for (int i = 0; i < sourceFiles.length; i++) { + log.info("顺序 {} -> {}", i + 1, sourceFiles[i]); + } + } + } catch (Exception ignore) {} + for (String filePath : sourceFiles) { + if (filePath == null || filePath.trim().isEmpty()) { + continue; + } + String lowerPath = filePath.toLowerCase(); + if (lowerPath.endsWith(".pdf")) { + pdfFiles.add(filePath); + } else if (lowerPath.endsWith(".ofd")) { + // 将 OFD 转换后的 PDF 命名为原始文件名.pdf(而非 UUID),保证排序与可读性 + String originalName = new File(filePath).getName(); + String baseName = originalName.endsWith(".ofd") ? originalName.substring(0, originalName.length() - 4) : originalName; + // 简单清洗,防止异常字符 + // 仅保留字母、数字、下划线、点和连字符,其他替换为下划线 + String sanitized = baseName.replaceAll("[^\\w.-]+", "_"); + Path outPath = Paths.get(tempDir, sanitized + ".pdf"); + int suffix = 1; + while (Files.exists(outPath)) { + outPath = Paths.get(tempDir, sanitized + "(" + (suffix++) + ").pdf"); + } + String tempPdfPath = outPath.toString(); + try { + OfdToPdfUtil.ofdToPdf(filePath, tempPdfPath); + pdfFiles.add(tempPdfPath); + tempFilesToDelete.add(tempPdfPath); + log.info("OFD转换成功: {} -> {}", filePath, tempPdfPath); + } catch (Exception e) { + log.error("OFD转换失败: {}", filePath, e); + } + } else { + log.warn("不支持的文件格式: {}", filePath); + } + } + + if (pdfFiles.isEmpty()) { + log.warn("没有可合并的PDF文件"); + return false; + } + try { + log.info("最终参与合并的PDF顺序(已按源文件名排序)共 {} 个:", pdfFiles.size()); + for (int i = 0; i < pdfFiles.size(); i++) { + log.info("合并顺序 {} -> {}", i + 1, pdfFiles.get(i)); + } + } catch (Exception ignore) {} + boolean mergeSuccess = mergePdfFiles( + pdfFiles.toArray(new String[0]), + targetFile + ); + return mergeSuccess; + + } finally { + cleanupTempFiles(tempFilesToDelete); + } + } + + /** + * 合并PDF文件(改进版) + */ + private static boolean mergePdfFiles(String[] fileArray, String targetFile) { + // 删除已存在的目标文件 + File target = new File(targetFile); + if (target.exists() && !target.delete()) { + log.error("无法删除已存在的目标文件: {}", targetFile); + return false; + } + + Document document = null; + PdfCopy pdfCopy = null; + + try { + document = new Document(); + pdfCopy = new PdfCopy(document, new FileOutputStream(targetFile)); + document.open(); + + int successCount = 0; + int totalPages = 0; + try { + log.info("mergePdfFiles 将合并 {} 个PDF,按如下顺序:", (fileArray == null ? 0 : fileArray.length)); + if (fileArray != null) { + for (int i = 0; i < fileArray.length; i++) { + log.info("合并顺序 {} -> {}", i + 1, fileArray[i]); + } + } + } catch (Exception ignore) {} + + for (String filePath : fileArray) { + PdfReader reader = null; + try { + reader = new PdfReader(filePath); + int pages = reader.getNumberOfPages(); + + // 逐页添加 + for (int i = 1; i <= pages; i++) { + pdfCopy.addPage(pdfCopy.getImportedPage(reader, i)); + } + + totalPages += pages; + successCount++; + log.info("已合并文件: {} ({}页)", filePath, pages); + + } catch (Exception e) { + log.error("处理文件失败: {}", filePath, e); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (Exception e) { + log.warn("关闭reader失败", e); + } + } + } + } + + log.info("合并完成: {}/{} 个文件, 共{}页", + successCount, fileArray.length, totalPages); + return successCount > 0; + + } catch (Exception e) { + log.error("合并PDF失败", e); + return false; + } finally { + if (document != null && document.isOpen()) { + document.close(); + } + } + } + + /** + * 清理临时文件 + */ + private static void cleanupTempFiles(List tempFiles) { + for (String tempFile : tempFiles) { + try { + Files.deleteIfExists(Paths.get(tempFile)); + log.debug("删除临时文件: {}", tempFile); + } catch (Exception e) { + log.warn("删除临时文件失败: {}", tempFile, e); + } + } + } } diff --git a/src/main/java/com/point/strategy/service/FileManageService.java b/src/main/java/com/point/strategy/service/FileManageService.java index 89749bb..3023cd7 100644 --- a/src/main/java/com/point/strategy/service/FileManageService.java +++ b/src/main/java/com/point/strategy/service/FileManageService.java @@ -34,7 +34,6 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; -import org.ofdrw.tool.merge.OFDMerger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -50,11 +49,10 @@ import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.io.*; import java.net.URLEncoder; -import java.nio.file.Path; -import java.nio.file.Paths; import java.text.SimpleDateFormat; -import java.util.List; +import java.nio.file.Paths; import java.util.*; +import java.util.List; import java.util.stream.Collectors; @Service @@ -176,13 +174,7 @@ public class FileManageService { } - public void batchDownload(String tableName, - String ids, - Integer userId, - String archiveNo, - Integer type, - HttpServletRequest request, - HttpServletResponse response) { + public void batchDownload(String tableName, String ids, Integer userId, String archiveNo, Integer type, HttpServletRequest request, HttpServletResponse response) { try { String zipBasePath = tempPath + "\\temp2\\bb\\"; FileUtil.makedir(zipBasePath); @@ -209,7 +201,7 @@ public class FileManageService { file_des = file_des + File.separator; } //String dir = imgUpload + File.separator + file_path + File.separator + file_name_server; - String dir = file_des + file_name_server; + String dir = file_des + file_name_server; filePaths.put(dir, file_name); } //打包成zip文件 并下载 @@ -238,10 +230,7 @@ public class FileManageService { } - public void batchDownloadTwo(String tableName, - String ids, - HttpServletRequest request, - HttpServletResponse response) { + public void batchDownloadTwo(String tableName, String ids, HttpServletRequest request, HttpServletResponse response) { try { //批量下载档案复制 String zipBasePath = tempPath + "\\temp2\\bb\\"; @@ -260,7 +249,7 @@ public class FileManageService { String file_path = StringUtil.formatMap(tempFile_map, "file_path"); String file_des = StringUtil.formatMap(tempFile_map, "file_des"); //String dir = imgUpload + File.separator + file_path + File.separator + file_name_server; - String dir = file_des + File.separator + file_name_server; + String dir = file_des + File.separator + file_name_server; String fileNameInZip = StringUtils.isNotEmpty(file_name) ? file_name : file_name_server; filesMap.put(dir, fileNameInZip); } @@ -273,13 +262,7 @@ public class FileManageService { } } - public void batchDownloadWatermarking(String tableName, - String ids, - Integer userId, - String archiveNo, - Integer type, - HttpServletRequest request, - HttpServletResponse response) { + public void batchDownloadWatermarking(String tableName, String ids, Integer userId, String archiveNo, Integer type, HttpServletRequest request, HttpServletResponse response) { try { String zipBasePath = tempPath + "\\temp2\\bb\\"; String zipFilePath = tempPath + "\\temp2\\cc\\"; @@ -339,18 +322,7 @@ public class FileManageService { List> mapList = getTableDataList(tableName, ids); String datetime = DateUtil.date2String(new Date(), 1); String entity = formatContentEntity(mapList, tableName); - result = "" + - "<电子文件封装包>" + - " <封装包格式描述>本EEP 根据中华人民共和国档案行业标准DA/T 48-2009《基于XML 的电子文件封装规范》生成" + - " <版本>2009" + - " <被签名对象 eep版本=\"2009\">" + - " <封装包类型>原始型" + - " <封装包类型描述>本封装包包含电子文件数据及其元数据,原始封装,未经修改" + - " <封装包创建时间>" + datetime + "" + - " <封装包创建单位>湖北典策档案科技发展有限公司/153-1234-2345 158-3456-4567/湖北典策档案科技发展有限公司(湖北省武汉市武昌区洪山路87号)" + - " <封装内容>" + - " <文件实体块>" - + entity + + result = "" + "<电子文件封装包>" + " <封装包格式描述>本EEP 根据中华人民共和国档案行业标准DA/T 48-2009《基于XML 的电子文件封装规范》生成" + " <版本>2009" + " <被签名对象 eep版本=\"2009\">" + " <封装包类型>原始型" + " <封装包类型描述>本封装包包含电子文件数据及其元数据,原始封装,未经修改" + " <封装包创建时间>" + datetime + "" + " <封装包创建单位>湖北典策档案科技发展有限公司/153-1234-2345 158-3456-4567/湖北典策档案科技发展有限公司(湖北省武汉市武昌区洪山路87号)" + " <封装内容>" + " <文件实体块>" + entity + // " <文件实体关系>" + // " <文件标识符/>" + // " <被关联文件标识符/>" + @@ -358,64 +330,7 @@ public class FileManageService { // " <关系/>" + // " <关系描述/>" + // " " + - " " + - " <业务实体块>" + - " <业务实体>" + - " <业务标识符/>" + - " <机构人员标识符/>" + - " <文件标识符/>" + - " <业务状态/>" + - " <业务行为>数据封包" + - " <行为时间>" + datetime + "" + - " <行为依据>依据中华人民共和国档案行业标准DA/T 48-2009《基于XML 的电子文件封装规范》生成" + - " <行为描述>数据封包" + - " " + - " " + - " <机构人员实体块>" + - " <机构人员实体>" + - " <机构人员标识符/>" + - " <机构人员类型/>" + - " <机构人员名称/>" + - " <组织机构代码/>" + - " <个人职位/>" + - " " + - " <机构人员实体关系>" + - " <机构人员标识符/>" + - " <被关联机构人员标识符/>" + - " <关系类型/>" + - " <关系/>" + - " <关系描述/>" + - " " + - " " + - " " + - " " + - " <电子签名块>" + - " <电子签名>" + - " <签名标识符/>" + - " <签名规则>签名算法:MD5withRSA编码规则:UTF-8" + - " <签名时间>" + datetime + "" + - " <签名人>系统管理员" + - " <签名结果>57O757uf566h55CG5ZGY" + - " <证书块>" + - " <证书/>" + - " <证书引用/>" + - " " + - " <签名算法标识/>" + - " " + - " " + - " <锁定签名>" + - " <被锁定签名标识符/>" + - " <签名规则>签名算法:MD5withRSA编码规则:UTF-8" + - " <签名时间>" + datetime + "" + - " <签名人>系统管理员" + - " <签名结果>5rmW5YyX5qGj5qGI5oqA5pyv56CU56m26Zmi5pyJ6ZmQ5YWs5Y+4LzE1My03NzA4LTg1MzkgMTU4 LTcxODEtNTkyNi/muZbljJfnnIHmoaPmoYjppobmoaPmoYjkv53miqTkuK3lv4PvvIjmuZbljJfn nIHmrabmsYnluILmrabmmIzljLrmtKrlsbHot684N+WPtyk=" + - " <证书块>" + - " <证书/>" + - " <证书引用/>" + - " " + - " <签名算法标识/>" + - " " + - ""; + " " + " <业务实体块>" + " <业务实体>" + " <业务标识符/>" + " <机构人员标识符/>" + " <文件标识符/>" + " <业务状态/>" + " <业务行为>数据封包" + " <行为时间>" + datetime + "" + " <行为依据>依据中华人民共和国档案行业标准DA/T 48-2009《基于XML 的电子文件封装规范》生成" + " <行为描述>数据封包" + " " + " " + " <机构人员实体块>" + " <机构人员实体>" + " <机构人员标识符/>" + " <机构人员类型/>" + " <机构人员名称/>" + " <组织机构代码/>" + " <个人职位/>" + " " + " <机构人员实体关系>" + " <机构人员标识符/>" + " <被关联机构人员标识符/>" + " <关系类型/>" + " <关系/>" + " <关系描述/>" + " " + " " + " " + " " + " <电子签名块>" + " <电子签名>" + " <签名标识符/>" + " <签名规则>签名算法:MD5withRSA编码规则:UTF-8" + " <签名时间>" + datetime + "" + " <签名人>系统管理员" + " <签名结果>57O757uf566h55CG5ZGY" + " <证书块>" + " <证书/>" + " <证书引用/>" + " " + " <签名算法标识/>" + " " + " " + " <锁定签名>" + " <被锁定签名标识符/>" + " <签名规则>签名算法:MD5withRSA编码规则:UTF-8" + " <签名时间>" + datetime + "" + " <签名人>系统管理员" + " <签名结果>5rmW5YyX5qGj5qGI5oqA5pyv56CU56m26Zmi5pyJ6ZmQ5YWs5Y+4LzE1My03NzA4LTg1MzkgMTU4 LTcxODEtNTkyNi/muZbljJfnnIHmoaPmoYjppobmoaPmoYjkv53miqTkuK3lv4PvvIjmuZbljJfn nIHmrabmsYnluILmrabmmIzljLrmtKrlsbHot684N+WPtyk=" + " <证书块>" + " <证书/>" + " <证书引用/>" + " " + " <签名算法标识/>" + " " + ""; return result; } @@ -440,73 +355,7 @@ public class FileManageService { String fondsname = fondMapper.getFondsNameByFondsCode(fonds_no); - String entity = "<文件实体>" + - " <聚合层次/>" + - " <来源>" + - " <档案馆名称>" + - " <档案馆代码>" + - " <全宗名称>" + fondsname + "" + - " <立档单位名称>" + fondsname + "" + - " " + - " <电子文件号>" + uuid + "" + - " <档号>" + - " <档号>" + archive_no + "" + - " <全宗号>" + fonds_no + "" + - " <目录号>" + mlh + "" + - " <年度>" + filing_year + "" + - " <保管期限>" + retention + "" + - " <机构或问题>" + - " <类别号>" + - " <室编案卷号>" + year_folder_no + "" + - " <馆编案卷号/>" + - " <室编件号>" + piece_no + "" + - " <页数>" + quantity + "" + - " " + - " <内容描述>" + - " <题名>" + maintitle + "" + - " <并列题名/>" + - " <副题名/>" + - " <说明题名文字/>" + - " <主题词 主题词表名称=\"\"/>" + - " <人名/>" + - " <摘要/>" + - " <分类号>" + archive_ctg_no + "" + - " <文件编号/>" + - " <责任者>" + responsibleby + "" + - " <日期>" + created_date + "" + - " <文种/>" + - " <紧急程度>" + - " <主送/>" + - " <抄送/>" + - " <密级>" + security_class + "" + - " <保密期限/>" + - " " + - " <形式特征>" + - " <文件组合类型/>" + - " <页数>" + - " <语种/>" + - " <稿本/>" + - " <件数/>" + - " " + - " <存储位置>" + - " <当前位置/>" + - " <脱机载体编号/>" + - " <脱机载体存址/>" + - " <缩微号/>" + - " " + - " <权限管理>" + - " <知识产权说明/>" + - " <授权>" + - " <授权行为/>" + - " <授权对象/>" + - " " + - " <控制标识/>" + - " " + - " <信息系统描述/>" + - " <附注/>" + - " <文件数据>" + wendang(tableName, id) + "" + - " <修改封装内容/>" + - " "; + String entity = "<文件实体>" + " <聚合层次/>" + " <来源>" + " <档案馆名称>" + " <档案馆代码>" + " <全宗名称>" + fondsname + "" + " <立档单位名称>" + fondsname + "" + " " + " <电子文件号>" + uuid + "" + " <档号>" + " <档号>" + archive_no + "" + " <全宗号>" + fonds_no + "" + " <目录号>" + mlh + "" + " <年度>" + filing_year + "" + " <保管期限>" + retention + "" + " <机构或问题>" + " <类别号>" + " <室编案卷号>" + year_folder_no + "" + " <馆编案卷号/>" + " <室编件号>" + piece_no + "" + " <页数>" + quantity + "" + " " + " <内容描述>" + " <题名>" + maintitle + "" + " <并列题名/>" + " <副题名/>" + " <说明题名文字/>" + " <主题词 主题词表名称=\"\"/>" + " <人名/>" + " <摘要/>" + " <分类号>" + archive_ctg_no + "" + " <文件编号/>" + " <责任者>" + responsibleby + "" + " <日期>" + created_date + "" + " <文种/>" + " <紧急程度>" + " <主送/>" + " <抄送/>" + " <密级>" + security_class + "" + " <保密期限/>" + " " + " <形式特征>" + " <文件组合类型/>" + " <页数>" + " <语种/>" + " <稿本/>" + " <件数/>" + " " + " <存储位置>" + " <当前位置/>" + " <脱机载体编号/>" + " <脱机载体存址/>" + " <缩微号/>" + " " + " <权限管理>" + " <知识产权说明/>" + " <授权>" + " <授权行为/>" + " <授权对象/>" + " " + " <控制标识/>" + " " + " <信息系统描述/>" + " <附注/>" + " <文件数据>" + wendang(tableName, id) + "" + " <修改封装内容/>" + " "; result = result + entity; } return result; @@ -526,22 +375,7 @@ public class FileManageService { String dir = file_des + File.separator + file_name_server; String kk = file_name_server.replaceAll(".jpg", ""); String encodeStr = Base64Utils.encode2(dir); - String wendangXml = " <文档>" + - " <文档标识符>修改0-文档0" + - " <文档序号>0" + - " <文档数据 文档数据ID=\"修改0-文档0-文档数据0\">" + - " <编码 编码ID=\"修改0-文档0-文档数据0-编码0\">" + - " <电子属性>" + - " <格式信息>" + file_type + "" + - " <计算机文件名>" + file_name_server + "" + - " <计算机文件大小>406.57" + - " " + - " <编码描述>本封装包中" + - " <反编码关键字>base64" + - " <编码数据>" + encodeStr + "" + - " " + - " " + - " "; + String wendangXml = " <文档>" + " <文档标识符>修改0-文档0" + " <文档序号>0" + " <文档数据 文档数据ID=\"修改0-文档0-文档数据0\">" + " <编码 编码ID=\"修改0-文档0-文档数据0-编码0\">" + " <电子属性>" + " <格式信息>" + file_type + "" + " <计算机文件名>" + file_name_server + "" + " <计算机文件大小>406.57" + " " + " <编码描述>本封装包中" + " <反编码关键字>base64" + " <编码数据>" + encodeStr + "" + " " + " " + " "; result = result + wendangXml; } return result; @@ -587,11 +421,7 @@ public class FileManageService { @Transactional - public AjaxJson transfer(String outPath, - Integer classId, - String ids, - HttpServletRequest request1, - HttpServletResponse response) { + public AjaxJson transfer(String outPath, Integer classId, String ids, HttpServletRequest request1, HttpServletResponse response) { AjaxJson result = null; try { result = new AjaxJson<>(); @@ -846,9 +676,7 @@ public class FileManageService { * @return */ private String getContentFileDirectory(List> dataList, String tableName) { - String result = "\n" + - "\n" + - "<文件目录>\n" + getContent(dataList, tableName) + "\n"; + String result = "\n" + "\n" + "<文件目录>\n" + getContent(dataList, tableName) + "\n"; return result; } @@ -857,9 +685,7 @@ public class FileManageService { String result = ""; for (Map map : dataList) { String ziduanbiaoqianContent = ziduanbiaoqian(tableName, map); - String content = "<文件>\n" + - ziduanbiaoqianContent - + " \n"; + String content = "<文件>\n" + ziduanbiaoqianContent + " \n"; result = result + content; } return result; @@ -881,9 +707,7 @@ public class FileManageService { //------案卷目录-------------start---------传统 private String getContentFileDirectoryChuangtong(List> dataList, String tableName) { - String result = "\n" + - "\n" + - "<档案目录>\n" + getContentChuangtong(dataList, tableName) + "\n"; + String result = "\n" + "\n" + "<档案目录>\n" + getContentChuangtong(dataList, tableName) + "\n"; return result; } @@ -891,9 +715,7 @@ public class FileManageService { String result = ""; for (Map map : dataList) { String ziduanbiaoqianContent = ziduanbiaoqian(tableName, map); - String content = "<档案>\n" + - ziduanbiaoqianContent - + " \n"; + String content = "<档案>\n" + ziduanbiaoqianContent + " \n"; result = result + content; } return result; @@ -905,9 +727,7 @@ public class FileManageService { private String getContentFileDirectoryXiangmu(List> dataList, String tableName) { - String result = "\n" + - "\n" + - "<项目目录>\n" + getContentXiangmu(dataList, tableName) + "\n"; + String result = "\n" + "\n" + "<项目目录>\n" + getContentXiangmu(dataList, tableName) + "\n"; return result; } @@ -915,9 +735,7 @@ public class FileManageService { String result = ""; for (Map map : dataList) { String ziduanbiaoqianContent = ziduanbiaoqian(tableName, map); - String content = "<项目>\n" + - ziduanbiaoqianContent - + " \n"; + String content = "<项目>\n" + ziduanbiaoqianContent + " \n"; result = result + content; } return result; @@ -936,11 +754,7 @@ public class FileManageService { * @return */ @Transactional - public AjaxJson archiveSeal(Integer id, - String tableName, - Integer fileId, - String archiveNo, - HttpServletRequest request) { + public AjaxJson archiveSeal(Integer id, String tableName, Integer fileId, String archiveNo, HttpServletRequest request) { AjaxJson result = null; try { result = new AjaxJson<>(); @@ -986,22 +800,22 @@ public class FileManageService { String file_name_server = StringUtil.formatMap(tempFile_map, "file_name_server"); String file_des = StringUtil.formatMap(tempFile_map, "file_des"); String file_name_server_pdf_original = ""; - if(file_name_server.contains(".jpg")){ + if (file_name_server.contains(".jpg")) { file_name_server_pdf_original = file_name_server.replace(".jpg", "_original.pdf"); - }else if(file_name_server.contains(".pdf")){ + } else if (file_name_server.contains(".pdf")) { file_name_server_pdf_original = file_name_server.replace(".pdf", "_original.pdf"); //String newName_pdf_original=file_name_server.replace(".pdf","_original.pdf"); //FileTool.copyFile(dir+File.separator+file_name_server,dir+File.separator+newName_pdf_original); String[][] textContent = {{fonds_no, filing_year, piece_no}, {jigouwenti, retention, quantity}}; - PdfFileHelper.Seal(file_des+File.separator+file_name_server_pdf_original, file_des+File.separator+file_name_server, 1, textContent, "2", 1); + PdfFileHelper.Seal(file_des + File.separator + file_name_server_pdf_original, file_des + File.separator + file_name_server, 1, textContent, "2", 1); return result; - }else if(file_name_server.contains(".ofd")){ - if(youhongIntegrate){ - String newName_pdf_original=file_name_server.replace(".ofd","_ArchiveSeal.ofd"); + } else if (file_name_server.contains(".ofd")) { + if (youhongIntegrate) { + String newName_pdf_original = file_name_server.replace(".ofd", "_ArchiveSeal.ofd"); //FileTool.copyFile(dir+File.separator+file_name_server,dir+File.separator+newName_pdf_original); - HTTPAgent agent = new HTTPAgent(youhongBaseUrl,5); - ArchiveStamp archiveStamp = new ArchiveStamp(0,255,0,0); + HTTPAgent agent = new HTTPAgent(youhongBaseUrl, 5); + ArchiveStamp archiveStamp = new ArchiveStamp(0, 255, 0, 0); archiveStamp.setIndex(new int[]{0}); archiveStamp.setxAlign(Const.XAlign.Center); archiveStamp.setyAlign(Const.YAlign.Top); @@ -1019,21 +833,15 @@ public class FileManageService { archiveStamp.setFontColor("#FF0000"); String[] content1 = {fonds_no, filing_year, piece_no}; - ArchiveStamp.CellStyle[] styles1 = { - new ArchiveStamp.CellStyle("Times New Roman",17.3,"#000000"), - new ArchiveStamp.CellStyle("Times New Roman",17.3,"#000000"), - new ArchiveStamp.CellStyle("Times New Roman",15.33,"#000000") + ArchiveStamp.CellStyle[] styles1 = {new ArchiveStamp.CellStyle("Times New Roman", 17.3, "#000000"), new ArchiveStamp.CellStyle("Times New Roman", 17.3, "#000000"), new ArchiveStamp.CellStyle("Times New Roman", 15.33, "#000000") }; String[] content2 = {jigouwenti, retention, quantity}; - ArchiveStamp.CellStyle[] styles2 = { - new ArchiveStamp.CellStyle("方正小标宋",18.6,"#000000"), - new ArchiveStamp.CellStyle("宋体",16.6,"#000000"), - new ArchiveStamp.CellStyle("Times New Roman",14,"#000000") + ArchiveStamp.CellStyle[] styles2 = {new ArchiveStamp.CellStyle("方正小标宋", 18.6, "#000000"), new ArchiveStamp.CellStyle("宋体", 16.6, "#000000"), new ArchiveStamp.CellStyle("Times New Roman", 14, "#000000") }; - archiveStamp.addRow(content1,styles1); - archiveStamp.addRow(content2,styles2); + archiveStamp.addRow(content1, styles1); + archiveStamp.addRow(content2, styles2); // archiveStamp.addRow(fonds_no, filing_year, piece_no); // archiveStamp.addRow(archive_ctg_no, retention, quantity); String result_file_des = file_des + "/result"; @@ -1041,9 +849,9 @@ public class FileManageService { if (!fileOne.exists()) { fileOne.mkdirs(); } - agent.officeToOFD(new File(file_des+File.separator+file_name_server),new FileOutputStream(result_file_des+File.separator+newName_pdf_original),null,archiveStamp); + agent.officeToOFD(new File(file_des + File.separator + file_name_server), new FileOutputStream(result_file_des + File.separator + newName_pdf_original), null, archiveStamp); //更新文件服务名 - String fieldValue = " file_name_server='" + newName_pdf_original + "'" + "," + " file_des ='" + result_file_des + "'"; + String fieldValue = " file_name_server='" + newName_pdf_original + "'" + "," + " file_des ='" + result_file_des + "'"; String conditionSql = " id='" + fileId + "'"; Map map7 = new HashMap(); map7.put("tableName", tableName + "_temp_file"); @@ -1121,15 +929,11 @@ public class FileManageService { * @return */ @Transactional - public AjaxJson mergeFile(String fondscode, - Integer id, - String fileIds, - String tableName, - String archiveNo, - HttpServletRequest request) { + public AjaxJson mergeFile(String fondscode, Integer id, String fileIds, String tableName, String archiveNo, HttpServletRequest request) { AjaxJson result = null; try { result = new AjaxJson<>(); + logger.info("mergeFile 入参: fondscode={}, id={}, fileIds={}, tableName={}, archiveNo={}", fondscode, id, fileIds, tableName, archiveNo); //判断已经合并pdf成功了,就不能再合并了 Map parasMap5 = new HashMap(); parasMap5.put("tableName", tableName + "_temp_file"); @@ -1149,18 +953,52 @@ public class FileManageService { Map parasMap2 = new HashMap(); parasMap2.put("tableName", tableName + "_temp_file"); if (fileIds != null && !"".equals(fileIds)) { - parasMap2.put("conditionSql", " id in (" + fileIds + " )"); + // 交由后续Java层按文件名中的数字片段排序 + parasMap2.put("conditionSql", " id in (" + fileIds + ")"); } else { + // 交由后续Java层按文件名中的数字片段排序 parasMap2.put("conditionSql", " file_status=1 and rec_id= " + id); } List> dataList2 = danganguanliMapper.selectObject(parasMap2); + logger.info("mergeFile 查询到待合并文件 {} 个(将按 file_name 数字片段正序排序)", (dataList2 == null ? 0 : dataList2.size())); + if (dataList2 != null) { + // 严格按 file_name 的数字片段正序排序;若 file_name 为空,将排在最后并记录告警 + try { + dataList2.sort((a, b) -> { + String an = StringUtil.formatMap(a, "file_name"); + String bn = StringUtil.formatMap(b, "file_name"); + boolean aBlank = StringUtils.isBlank(an); + boolean bBlank = StringUtils.isBlank(bn); + if (aBlank && bBlank) return 0; + if (aBlank) return 1; // 空的靠后 + if (bBlank) return -1; + return new FileNameComparator().compare(an, bn); + }); + int row = 0; + for (Map m : dataList2) { + row++; + String logId = StringUtil.formatMap(m, "id"); + String logFname = StringUtil.formatMap(m, "file_name"); + String logSrv = StringUtil.formatMap(m, "file_name_server"); + if (StringUtils.isBlank(logFname)) { + logger.warn("记录 id={} 的 file_name 为空,已排在末尾;file_name_server={}", logId, logSrv); + } + logger.info("排序后顺序 {} -> id={}, file_name={}, file_name_server={}", row, logId, logFname, logSrv); + } + } catch (Exception e) { + logger.warn("mergeFile 按 file_name 排序时出现异常,将按原顺序合并", e); + } + } //临时文件夹 String temp_pdf = tempPath + "/temp_company_img/"; FileUtil.makedir(temp_pdf); + String temp_merge = tempPath + "/tmp_merge"; + FileUtil.makedir(temp_merge); //合并文件 String[] fileArray = new String[dataList2.size()]; int i = 0; + int orderNo = 0; for (Map tempFile_map : dataList2) { String file_name_server = StringUtil.formatMap(tempFile_map, "file_name_server"); String file_name_server_pdf = file_name_server.replace(".jpg", "_original.pdf"); @@ -1170,18 +1008,25 @@ public class FileManageService { if (!file.exists()) { srcpdfPath = dir1 + file_name_server_pdf; fileArray[i] = srcpdfPath; + orderNo++; + logger.info("合并顺序 {} -> {} (来源: {})", orderNo, srcpdfPath, "archiveNo 目录"); i++; } else { fileArray[i] = srcpdfPath; + orderNo++; + logger.info("合并顺序 {} -> {} (来源: {})", orderNo, srcpdfPath, "临时目录"); i++; } } + // 最终不再按物理文件名排序,确保顺序来源于 file_name String tarFile = temp_pdf + StringUtil.generaterUUID() + ".pdf"; - PdfFileHelper.mergePdf(fileArray, tarFile); + logger.info("调用 PdfFileHelper.mergeOfdAndPdf 开始合并,目标文件: {}", tarFile); + PdfFileHelper.mergeOfdAndPdf(fileArray, tarFile, temp_merge); //要加编号 String tarFile2 = temp_pdf + StringUtil.generaterUUID() + ".pdf"; + logger.info("开始加页码,源: {} -> 目标: {}", tarFile, tarFile2); PdfFileHelper.pageNo(tarFile, tarFile2); //加归档章 @@ -1212,28 +1057,15 @@ public class FileManageService { FileUtil2.makedir(dir + File.separator); String target = dir + File.separator + myuuid + ".pdf"; String[][] textContent = {{fonds_no, filing_year, piece_no}, {archive_ctg_no, retention, quantity}}; + logger.info("开始加归档章,目标: {}", target); PdfFileHelper.Seal(tarFile2, target, 1, textContent, "1", 2); //pdf转ofd String newName_ofd = target.replace(".pdf", ".ofd"); PdfToOfdUtil.pdfToOfd(target, newName_ofd); //最后把合并的pdf文件添加到temp_file中 - String fieldName = - "rec_id, " + - "file_name, " + - "file_name_server, " + - "file_path, " + - "file_type," + - "page_no," + - "file_status"; - String valueName = - "" + id + "," + - "'合并文件.pdf'," + - "'" + myuuid + ".pdf'," + - "'" + relative_path + "'," + - "'pdf'," + - "-1," + - "1"; + String fieldName = "rec_id, " + "file_name, " + "file_name_server, " + "file_path, " + "file_type," + "page_no," + "file_status"; + String valueName = "" + id + "," + "'合并文件.pdf'," + "'" + myuuid + ".pdf'," + "'" + relative_path + "'," + "'pdf'," + "-1," + "1"; Map map = new HashMap(); map.put("tableName", tableName + "_temp_file"); map.put("fieldName", fieldName); @@ -1264,14 +1096,7 @@ public class FileManageService { * @param tableName * @return */ - public void mergeDownload(String fondscode, - Integer id, - String fileIds, - String tableName, - String archiveNo, - HttpServletRequest request, - HttpServletResponse response, - Integer type) { + public void mergeDownload(String fondscode, Integer id, String fileIds, String tableName, String archiveNo, HttpServletRequest request, HttpServletResponse response, Integer type) { logger.info("开始合并下载流程,文件ID: {}, 表名: {}", fileIds, tableName); List tempFilesForCleanup = new ArrayList<>(); try { @@ -1291,14 +1116,45 @@ public class FileManageService { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } - logger.info("找到 {} 个待处理文件。", dataList2.size()); + logger.info("找到 {} 个待处理文件(将严格按 file_name 数字片段正序排序)。", dataList2.size()); + // 严格按 file_name 排序;若 file_name 为空,则排至末尾并记录告警 + try { + dataList2.sort((a, b) -> { + String an = StringUtil.formatMap(a, "file_name"); + String bn = StringUtil.formatMap(b, "file_name"); + boolean aBlank = StringUtils.isBlank(an); + boolean bBlank = StringUtils.isBlank(bn); + if (aBlank && bBlank) return 0; + if (aBlank) return 1; + if (bBlank) return -1; + return new FileNameComparator().compare(an, bn); + }); + int idx = 0; + for (Map m : dataList2) { + idx++; + String fn = StringUtil.formatMap(m, "file_name"); + if (StringUtils.isBlank(fn)) { + logger.warn("记录 id={} 的 file_name 为空,已排至末尾。file_name_server={}", + StringUtil.formatMap(m, "id"), StringUtil.formatMap(m, "file_name_server")); + } + logger.info("排序后顺序 {} -> id={}, file_name={}, file_name_server={}", idx, + StringUtil.formatMap(m, "id"), + fn, + StringUtil.formatMap(m, "file_name_server")); + } + } catch (Exception e) { + logger.warn("按 file_name 排序失败,将按数据库返回顺序处理。", e); + } String temp_pdf = tempPath + "/temp_company_img/"; FileUtil.makedir(temp_pdf); List fileList = new ArrayList<>(); + // 记录每个源OFD的期望目标PDF路径(基于 file_name 命名) + Map ofdTargetMap = new LinkedHashMap<>(); UserRole userRole = userService.getUserRole(request); String userChnName = userRole.getUser().getUserChnName(); for (Map tempFile_map : dataList2) { String file_name_server = StringUtil.formatMap(tempFile_map, "file_name_server"); + String file_name = StringUtil.formatMap(tempFile_map, "file_name"); String file_des = StringUtil.formatMap(tempFile_map, "file_des"); String srcPath = file_des + File.separator + file_name_server; logger.info("正在处理文件: {}", srcPath); @@ -1309,21 +1165,59 @@ public class FileManageService { extension = file_name_server.substring(dotIndex).toLowerCase(); } + // 计算基于原始 file_name 的期望PDF名称 + String desiredBase = file_name; + if (StringUtils.isBlank(desiredBase)) { + desiredBase = new File(file_name_server).getName(); + } + // 去除扩展名 + int fnDot = desiredBase.lastIndexOf('.'); + if (fnDot >= 0) desiredBase = desiredBase.substring(0, fnDot); + // 简单清洗:仅保留字母、数字、下划线、点和连字符(覆盖多语言) + desiredBase = desiredBase.replaceAll("[^\\p{L}\\p{N}_.-]+", "_"); + if (extension.equals(".jpg") || extension.equals(".png") || extension.equals(".jpeg")) { - String srcpdfPath = destFilePdf(srcPath, userChnName); + // 目标PDF放在 temp_pdf,按原始名命名 + String targetPdf = Paths.get(temp_pdf, desiredBase + ".pdf").toString(); + // 冲突时追加(序号) + int suffix = 1; + while (new File(targetPdf).exists()) { + targetPdf = Paths.get(temp_pdf, desiredBase + "(" + (suffix++) + ").pdf").toString(); + } + String srcpdfPath = destFilePdf(srcPath, targetPdf, userChnName); if (srcpdfPath != null) { logger.info("成功将图片 {} 转换为PDF: {}", srcPath, srcpdfPath); fileList.add(srcpdfPath); tempFilesForCleanup.add(new File(srcpdfPath)); - tempFilesForCleanup.add(new File(srcpdfPath.replace(".pdf", ".jpg"))); + // 同目录下的水印JPG + tempFilesForCleanup.add(new File(srcpdfPath.substring(0, srcpdfPath.length()-4) + "_waterMark.jpg")); } else { logger.error("处理并转换图片文件失败: {}", srcPath); } } else if (extension.equals(".pdf")) { - logger.info("文件已经是PDF格式,将直接合并: {}", srcPath); - fileList.add(srcPath); + // 已是PDF,也复制到临时目录并以原始 file_name 命名,确保命名与排序一致 + String targetPdf = Paths.get(temp_pdf, desiredBase + ".pdf").toString(); + int suffix = 1; + while (new File(targetPdf).exists()) { + targetPdf = Paths.get(temp_pdf, desiredBase + "(" + (suffix++) + ").pdf").toString(); + } + try { + FileUtils.copyFile(new File(srcPath), new File(targetPdf)); + logger.info("PDF复制完成: {} -> {}", srcPath, targetPdf); + fileList.add(targetPdf); + tempFilesForCleanup.add(new File(targetPdf)); + } catch (IOException e) { + logger.error("复制PDF到临时目录失败: {} -> {}", srcPath, targetPdf, e); + } } else if (extension.equals(".ofd")) { - logger.info("文件是OFD格式,将直接合并: {}", srcPath); + logger.info("文件是OFD格式,将直接合并(稍后转PDF): {}", srcPath); + // 预先计算目标PDF路径(基于原始 file_name 命名)供后续转换使用 + String targetPdf = Paths.get(temp_pdf, desiredBase + ".pdf").toString(); + int suffix = 1; + while (new File(targetPdf).exists()) { + targetPdf = Paths.get(temp_pdf, desiredBase + "(" + (suffix++) + ").pdf").toString(); + } + ofdTargetMap.put(srcPath, targetPdf); fileList.add(srcPath); } else { logger.warn("不支持合并的文件类型: {}. 已跳过此文件。", srcPath); @@ -1349,7 +1243,18 @@ public class FileManageService { pdfFileList.add(filePath); } else if (filePath.toLowerCase().endsWith(".ofd")) { // OFD文件转换为PDF - String pdfPath = temp_pdf + StringUtil.generaterUUID() + ".pdf"; + // 使用基于 file_name 的目标PDF路径 + String pdfPath = ofdTargetMap.getOrDefault(filePath, + Paths.get(temp_pdf, new File(filePath).getName().replaceAll("(?i)\\.ofd$", ".pdf")).toString()); + // 若仍冲突则追加(序号) + int suffix = 1; + while (new File(pdfPath).exists()) { + // 插入(序号)在扩展名前 + int dot = pdfPath.lastIndexOf('.'); + String base = dot >= 0 ? pdfPath.substring(0, dot) : pdfPath; + String ext = dot >= 0 ? pdfPath.substring(dot) : ".pdf"; + pdfPath = base + "(" + (suffix++) + ")" + ext; + } try { OfdToPdfUtil.ofdToPdf(filePath, pdfPath); pdfFileList.add(pdfPath); @@ -1372,7 +1277,10 @@ public class FileManageService { String tarFile = temp_pdf + StringUtil.generaterUUID() + ".pdf"; tempFilesForCleanup.add(new File(tarFile)); logger.info("正在将 {} 个PDF文件合并到 {}", pdfFileList.size(), tarFile); - PdfFileHelper.mergePdf(pdfFileList.toArray(new String[0]), tarFile); +// PdfFileHelper.mergePdf(pdfFileList.toArray(new String[0]), tarFile); + String temp_merge = tempPath + "/tmp_merge"; + FileUtil.makedir(temp_merge); + PdfFileHelper.mergeOfdAndPdf(pdfFileList.toArray(new String[0]), tarFile, temp_merge); File mergedFile = new File(tarFile); if (!mergedFile.exists() || mergedFile.length() == 0) { @@ -1391,7 +1299,10 @@ public class FileManageService { String tarFile = temp_pdf + StringUtil.generaterUUID() + ".pdf"; tempFilesForCleanup.add(new File(tarFile)); logger.info("正在将 {} 个PDF文件合并到 {}", fileList.size(), tarFile); - PdfFileHelper.mergePdf(fileList.toArray(new String[0]), tarFile); + String temp_merge = tempPath + "/tmp_merge"; + FileUtil.makedir(temp_merge); +// PdfFileHelper.mergePdf(fileList.toArray(new String[0]), tarFile); + PdfFileHelper.mergeOfdAndPdf(fileList.toArray(new String[0]), tarFile, temp_merge); File mergedFile = new File(tarFile); if (!mergedFile.exists() || mergedFile.length() == 0) { @@ -1456,7 +1367,7 @@ public class FileManageService { } } - private String destFilePdf(String srcImg, String userChnName) { + private String destFilePdf(String srcImg, String targetPdfPath, String userChnName) { File srcFile = new File(srcImg); if (!srcFile.exists() || srcFile.length() == 0) { logger.error("源图片文件不存在或是空的: {}", srcImg); @@ -1469,12 +1380,16 @@ public class FileManageService { logger.error("无法处理没有扩展名的文件: " + srcImg); return null; } - String baseName = srcImg.substring(0, lastDotIndex); - String destImg = baseName + "_waterMark.jpg"; + // 目标PDF所在目录与基名 + File targetPdfFile = new File(targetPdfPath); + String targetDir = targetPdfFile.getParent(); + String targetBase = targetPdfFile.getName(); + int tDot = targetBase.lastIndexOf('.'); + if (tDot >= 0) targetBase = targetBase.substring(0, tDot); + String destImg = Paths.get(targetDir, targetBase + "_waterMark.jpg").toString(); logger.info("正在添加水印: {} -> {}", srcImg, destImg); try { - ImgUtil.pressText( - cn.hutool.core.io.FileUtil.file(srcImg), //源图片 + ImgUtil.pressText(cn.hutool.core.io.FileUtil.file(srcImg), //源图片 cn.hutool.core.io.FileUtil.file(destImg), //目标图片 userChnName + "(内部资料)", //水印文字 Color.red, //水印文字颜色 @@ -1496,7 +1411,7 @@ public class FileManageService { logger.info("带水印的图片文件 {} 的大小: {} 字节", destImg, watermarkedFile.length()); String fromPath = destImg; - String toSource = baseName + "_waterMark.pdf"; + String toSource = targetPdfPath; logger.info("正在将带水印的图片转换为PDF: {} -> {}", fromPath, toSource); Img2pdf.jpg2pdfSortedByFilename(fromPath, toSource); @@ -1702,28 +1617,28 @@ public class FileManageService { } - private List> formatDataList(List> dataList,String funcTypeCode,String tableName){ - List> dataListResult =new ArrayList<>(); - for (Map map:dataList) { + private List> formatDataList(List> dataList, String funcTypeCode, String tableName) { + List> dataListResult = new ArrayList<>(); + for (Map map : dataList) { - String tableNameTiaoMu=""; - String tableNameYuanwen=""; - if (funcTypeCode==null ||"".equals(funcTypeCode)){ - tableNameTiaoMu=tableName; - tableNameYuanwen=tableName + "_file"; - }else { - tableNameTiaoMu=tableName + "_" + funcTypeCode; - tableNameYuanwen=tableName + "_" + funcTypeCode + "_file"; + String tableNameTiaoMu = ""; + String tableNameYuanwen = ""; + if (funcTypeCode == null || "".equals(funcTypeCode)) { + tableNameTiaoMu = tableName; + tableNameYuanwen = tableName + "_file"; + } else { + tableNameTiaoMu = tableName + "_" + funcTypeCode; + tableNameYuanwen = tableName + "_" + funcTypeCode + "_file"; } - String zhujianId=StringUtil.formatMap(map, "id"); + String zhujianId = StringUtil.formatMap(map, "id"); //得到主表--原文图片数据列表 Map parasMapFile = new HashMap(); parasMapFile.put("tableName", tableNameYuanwen); parasMapFile.put("conditionSql", " rec_id in ( " + zhujianId + " ) and file_status=1 "); - List> dataFile= danganguanliMapper.selectObject(parasMapFile); - int sumFile=0; - for (Map map22:dataFile) { + List> dataFile = danganguanliMapper.selectObject(parasMapFile); + int sumFile = 0; + for (Map map22 : dataFile) { String file_name_server = StringUtil.formatMap(map22, "file_name_server"); @@ -1736,28 +1651,28 @@ public class FileManageService { //String dir = imgUpload + File.separator + file_path + File.separator + file_name_server; int count = 0; String file_type = StringUtil.formatMap(map22, "file_type"); - if(file_type.equalsIgnoreCase("tif")){ + if (file_type.equalsIgnoreCase("tif")) { file_name_server = file_name_server.replaceAll(".jpg", ".pdf"); - String dir = file_des + file_name_server; - count= PdfFileHelper.getTifPageCount(dir); - }else{ + String dir = file_des + file_name_server; + count = PdfFileHelper.getTifPageCount(dir); + } else { file_name_server = file_name_server.replaceAll(".jpg", ".pdf"); - String dir = file_des + file_name_server; - count= PdfFileHelper.getPdfPageCoun(dir); + String dir = file_des + file_name_server; + count = PdfFileHelper.getPdfPageCoun(dir); } System.out.println(count); - sumFile=sumFile+count; + sumFile = sumFile + count; } - map.put("archive_file_num",sumFile); - String archive_file_num=String.valueOf(sumFile); + map.put("archive_file_num", sumFile); + String archive_file_num = String.valueOf(sumFile); //todo 查询页数兼容yeshu - String quantity=StringUtil.formatMap(map,"quantity"); - String yeshu=StringUtil.formatMap(map,"yeshu"); - if (!org.springframework.util.StringUtils.isEmpty(yeshu)){ - map.put("quantity",yeshu); + String quantity = StringUtil.formatMap(map, "quantity"); + String yeshu = StringUtil.formatMap(map, "yeshu"); + if (!org.springframework.util.StringUtils.isEmpty(yeshu)) { + map.put("quantity", yeshu); } - if (quantity==null || "".equals(quantity)){ - quantity="0"; + if (quantity == null || "".equals(quantity)) { + quantity = "0"; } dataListResult.add(map); // if (!archive_file_num.equals(quantity)){ @@ -1767,18 +1682,12 @@ public class FileManageService { return dataListResult; } - public void downloadExcel2(String ids, - String mapOne, - String tableName, - String funcTypeCode, - String downloadInfo, - HttpServletRequest request, - HttpServletResponse response) { + public void downloadExcel2(String ids, String mapOne, String tableName, String funcTypeCode, String downloadInfo, HttpServletRequest request, HttpServletResponse response) { try { Map mapTwo = JSON.parseObject(mapOne); JSONObject downloadInfoObj = JSON.parseObject(downloadInfo); - Integer level=downloadInfoObj.getInteger("level"); - Integer sign=downloadInfoObj.getInteger("sign"); + Integer level = downloadInfoObj.getInteger("level"); + Integer sign = downloadInfoObj.getInteger("sign"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); @@ -1799,8 +1708,8 @@ public class FileManageService { cols1 = "archive_no"; } } - String[] columnsTitle = {"档号","原文数量","条目页数"}; - String cols[] = {cols1,"archive_file_num","quantity"}; + String[] columnsTitle = {"档号", "原文数量", "条目页数"}; + String cols[] = {cols1, "archive_file_num", "quantity"}; HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("文书传统整理"); HSSFRow row = sheet.createRow(0); @@ -1867,18 +1776,18 @@ public class FileManageService { parasMap2.put("conditionSql", " id in ( " + ids + " )"); } List> dataList = danganguanliMapper.selectObject(parasMap2); - dataList=formatDataList(dataList,funcTypeCode,tableName); + dataList = formatDataList(dataList, funcTypeCode, tableName); for (int i = 0; i < dataList.size(); i++) { HSSFRow rowi = sheet.createRow(i + 1); Map map = dataList.get(i); int num = 0; for (String key : cols) { - String cellValue=""; - String val=StringUtil.formatMap(map, key); - if (val!=null&&!"".equals(val)){ - cellValue=val; - }else{ - cellValue="0"; + String cellValue = ""; + String val = StringUtil.formatMap(map, key); + if (val != null && !"".equals(val)) { + cellValue = val; + } else { + cellValue = "0"; } rowi.createCell(num).setCellValue(cellValue); num++; @@ -1895,7 +1804,6 @@ public class FileManageService { } - @Transactional public AjaxJson contrastField(String filePath, Integer classId, HttpServletResponse response) { AjaxJson result = null; @@ -2120,9 +2028,7 @@ public class FileManageService { * @return */ //@Transactional - public AjaxJson receive(ReceiveDto receiveDto, - HttpServletRequest request, - HttpServletResponse response) { + public AjaxJson receive(ReceiveDto receiveDto, HttpServletRequest request, HttpServletResponse response) { AjaxJson result = null; try { result = new AjaxJson<>(); @@ -2192,24 +2098,8 @@ public class FileManageService { String dir = imgUpload + relative_path; //原文图片也要添加到表中 //把数据添加到表中 - String fieldNameFile = - "rec_id, " + - "file_name, " + - "file_name_server, " + - "file_path, " + - "file_type," + - "page_no," + - "file_des," + - "file_status"; - String valueNameFile = - "" + id + "," + - "'" + myuuid + ".jpg'," + - "'" + myuuid + ".jpg'," + - "'" + relative_path + "'," + - "'jpg'," + - "-1," + - "'" + dir + "'," + - "1"; + String fieldNameFile = "rec_id, " + "file_name, " + "file_name_server, " + "file_path, " + "file_type," + "page_no," + "file_des," + "file_status"; + String valueNameFile = "" + id + "," + "'" + myuuid + ".jpg'," + "'" + myuuid + ".jpg'," + "'" + relative_path + "'," + "'jpg'," + "-1," + "'" + dir + "'," + "1"; Map mapFile = new HashMap(); mapFile.put("tableName", tableName + "_temp_file"); //其实我们知道是哪些字段 @@ -2218,14 +2108,11 @@ public class FileManageService { danganguanliMapper.saveObject(mapFile); //原文也要复制到项目中图片库中 FileUtil.makedir(dir); - FileTool.copyTo(strJpgPaht, - dir + "/" + myuuid + ".jpg"); + FileTool.copyTo(strJpgPaht, dir + "/" + myuuid + ".jpg"); //要生成pdf文件 - PdfFileHelper.image2Pdf(dir + "/" + myuuid + ".jpg", - dir + "/" + myuuid + ".pdf"); + PdfFileHelper.image2Pdf(dir + "/" + myuuid + ".jpg", dir + "/" + myuuid + ".pdf"); //要生成pdf文件-要保留原始pdf一份 - FileTool.copyTo(dir + "/" + myuuid + ".pdf", - dir + "/" + myuuid + "_original.pdf"); + FileTool.copyTo(dir + "/" + myuuid + ".pdf", dir + "/" + myuuid + "_original.pdf"); } } } @@ -2292,24 +2179,8 @@ public class FileManageService { String dir = imgUpload + relative_path; //原文图片也要添加到表中 //把数据添加到表中 - String fieldNameFile = - "rec_id, " + - "file_name, " + - "file_name_server, " + - "file_path, " + - "file_type," + - "page_no," + - "file_des," + - "file_status"; - String valueNameFile = - "" + id + "," + - "'" + myuuid + ".jpg'," + - "'" + myuuid + ".jpg'," + - "'" + relative_path + "'," + - "'jpg'," + - "-1," + - "'" + dir + "'," + - "1"; + String fieldNameFile = "rec_id, " + "file_name, " + "file_name_server, " + "file_path, " + "file_type," + "page_no," + "file_des," + "file_status"; + String valueNameFile = "" + id + "," + "'" + myuuid + ".jpg'," + "'" + myuuid + ".jpg'," + "'" + relative_path + "'," + "'jpg'," + "-1," + "'" + dir + "'," + "1"; Map mapFile = new HashMap(); mapFile.put("tableName", tableName + "_temp_file"); mapFile.put("fieldName", fieldNameFile); @@ -2317,14 +2188,11 @@ public class FileManageService { danganguanliMapper.saveObject(mapFile); //原文也要复制到项目中图片库中 FileUtil.makedir(dir); - FileTool.copyTo(strJpgPaht, - dir + "/" + myuuid + ".jpg"); + FileTool.copyTo(strJpgPaht, dir + "/" + myuuid + ".jpg"); //要生成pdf文件 - PdfFileHelper.image2Pdf(dir + "/" + myuuid + ".jpg", - dir + "/" + myuuid + ".pdf"); + PdfFileHelper.image2Pdf(dir + "/" + myuuid + ".jpg", dir + "/" + myuuid + ".pdf"); //要生成pdf文件-要保留原始pdf一份 - FileTool.copyTo(dir + "/" + myuuid + ".pdf", - dir + "/" + myuuid + "_original.pdf"); + FileTool.copyTo(dir + "/" + myuuid + ".pdf", dir + "/" + myuuid + "_original.pdf"); } } } @@ -2382,24 +2250,8 @@ public class FileManageService { String dir = imgUpload + relative_path; //原文图片也要添加到表中 //把数据添加到表中 - String fieldNameFile = - "rec_id, " + - "file_name, " + - "file_name_server, " + - "file_path, " + - "file_type," + - "page_no," + - "file_des," + - "file_status"; - String valueNameFile = - "" + id + "," + - "'" + myuuid + ".jpg'," + - "'" + myuuid + ".jpg'," + - "'" + relative_path + "'," + - "'jpg'," + - "-1," + - "'" + dir + "'," + - "1"; + String fieldNameFile = "rec_id, " + "file_name, " + "file_name_server, " + "file_path, " + "file_type," + "page_no," + "file_des," + "file_status"; + String valueNameFile = "" + id + "," + "'" + myuuid + ".jpg'," + "'" + myuuid + ".jpg'," + "'" + relative_path + "'," + "'jpg'," + "-1," + "'" + dir + "'," + "1"; Map mapFile = new HashMap(); mapFile.put("tableName", tableName2 + "_temp_file"); mapFile.put("fieldName", fieldNameFile); @@ -2407,14 +2259,11 @@ public class FileManageService { danganguanliMapper.saveObject(mapFile); //原文也要复制到项目中图片库中 FileUtil.makedir(dir); - FileTool.copyTo(strJpgPaht, - dir + "/" + myuuid + ".jpg"); + FileTool.copyTo(strJpgPaht, dir + "/" + myuuid + ".jpg"); //要生成pdf文件 - PdfFileHelper.image2Pdf(dir + "/" + myuuid + ".jpg", - dir + "/" + myuuid + ".pdf"); + PdfFileHelper.image2Pdf(dir + "/" + myuuid + ".jpg", dir + "/" + myuuid + ".pdf"); //要生成pdf文件-要保留原始pdf一份 - FileTool.copyTo(dir + "/" + myuuid + ".pdf", - dir + "/" + myuuid + "_original.pdf"); + FileTool.copyTo(dir + "/" + myuuid + ".pdf", dir + "/" + myuuid + "_original.pdf"); } } } @@ -2669,24 +2518,8 @@ public class FileManageService { String dir = imgUpload + relative_path; //原文图片也要添加到表中 //把数据添加到表中 - String fieldNameFile = - "rec_id, " + - "file_name, " + - "file_name_server, " + - "file_path, " + - "file_type," + - "page_no," + - "file_des," + - "file_status"; - String valueNameFile = - "" + id + "," + - "'" + myuuid + ".jpg'," + - "'" + myuuid + ".jpg'," + - "'" + relative_path + "'," + - "'jpg'," + - "-1," + - "'" + dir + "'," + - "1"; + String fieldNameFile = "rec_id, " + "file_name, " + "file_name_server, " + "file_path, " + "file_type," + "page_no," + "file_des," + "file_status"; + String valueNameFile = "" + id + "," + "'" + myuuid + ".jpg'," + "'" + myuuid + ".jpg'," + "'" + relative_path + "'," + "'jpg'," + "-1," + "'" + dir + "'," + "1"; Map mapFile = new HashMap(); mapFile.put("tableName", tableName3 + "_temp_file"); mapFile.put("fieldName", fieldNameFile); @@ -2694,14 +2527,11 @@ public class FileManageService { danganguanliMapper.saveObject(mapFile); //原文也要复制到项目中图片库中 FileUtil.makedir(dir); - FileTool.copyTo(strJpgPaht, - dir + "/" + myuuid + ".jpg"); + FileTool.copyTo(strJpgPaht, dir + "/" + myuuid + ".jpg"); //要生成pdf文件 - PdfFileHelper.image2Pdf(dir + "/" + myuuid + ".jpg", - dir + "/" + myuuid + ".pdf"); + PdfFileHelper.image2Pdf(dir + "/" + myuuid + ".jpg", dir + "/" + myuuid + ".pdf"); //要生成pdf文件-要保留原始pdf一份 - FileTool.copyTo(dir + "/" + myuuid + ".pdf", - dir + "/" + myuuid + "_original.pdf"); + FileTool.copyTo(dir + "/" + myuuid + ".pdf", dir + "/" + myuuid + "_original.pdf"); } } } @@ -2713,9 +2543,7 @@ public class FileManageService { } - public AjaxJson receiveEEP(@RequestBody JSONObject jsonObject, - HttpServletRequest request, - HttpServletResponse response) { + public AjaxJson receiveEEP(@RequestBody JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) { AjaxJson result = null; try { result = new AjaxJson<>(); @@ -2787,24 +2615,8 @@ public class FileManageService { Base64Utils.decode2(strJpgPaht, 编码数据Base64); //原文图片也要添加到表中 //把数据添加到表中 - String fieldNameFile = - "rec_id, " + - "file_name, " + - "file_name_server, " + - "file_path, " + - "file_type," + - "page_no," + - "file_des," + - "file_status"; - String valueNameFile = - "" + id + "," + - "'" + myuuid + ".jpg'," + - "'" + myuuid + ".jpg'," + - "'" + relative_path + "'," + - "'jpg'," + - "-1," + - "'" + dir + "'," + - "1"; + String fieldNameFile = "rec_id, " + "file_name, " + "file_name_server, " + "file_path, " + "file_type," + "page_no," + "file_des," + "file_status"; + String valueNameFile = "" + id + "," + "'" + myuuid + ".jpg'," + "'" + myuuid + ".jpg'," + "'" + relative_path + "'," + "'jpg'," + "-1," + "'" + dir + "'," + "1"; Map mapFile = new HashMap(); mapFile.put("tableName", tableName + "_temp_file"); //其实我们知道是哪些字段 @@ -2815,11 +2627,9 @@ public class FileManageService { FileUtil.makedir(dir); //要生成pdf文件 - PdfFileHelper.image2Pdf(dir + "/" + myuuid + ".jpg", - dir + "/" + myuuid + ".pdf"); + PdfFileHelper.image2Pdf(dir + "/" + myuuid + ".jpg", dir + "/" + myuuid + ".pdf"); //要生成pdf文件-要保留原始pdf一份 - FileTool.copyTo(dir + "/" + myuuid + ".pdf", - dir + "/" + myuuid + "_original.pdf"); + FileTool.copyTo(dir + "/" + myuuid + ".pdf", dir + "/" + myuuid + "_original.pdf"); } } } @@ -3735,7 +3545,7 @@ public class FileManageService { String[] fileIdArray = md5_code.split(","); for (String fileId : fileIdArray) { - if(StringUtils.isNotEmpty(fileId)){ + if (StringUtils.isNotEmpty(fileId)) { String fieldValue = " rec_id=" + myId + ",file_status=1"; String conditionSql = " id='" + fileId + "'"; Map map7 = new HashMap(); @@ -4047,14 +3857,14 @@ public class FileManageService { Integer zhujianId = jsonObject.getInteger("id"); String tableName = jsonObject.getString("tableName"); String funcTypeCode = jsonObject.getString("funcTypeCode"); - String tableNameTiaoMu=""; - String tableNameYuanwen=""; - if (funcTypeCode==null ||"".equals(funcTypeCode)){ - tableNameTiaoMu=tableName; - tableNameYuanwen=tableName + "_file"; - }else { - tableNameTiaoMu=tableName + "_" + funcTypeCode; - tableNameYuanwen=tableName + "_" + funcTypeCode + "_file"; + String tableNameTiaoMu = ""; + String tableNameYuanwen = ""; + if (funcTypeCode == null || "".equals(funcTypeCode)) { + tableNameTiaoMu = tableName; + tableNameYuanwen = tableName + "_file"; + } else { + tableNameTiaoMu = tableName + "_" + funcTypeCode; + tableNameYuanwen = tableName + "_" + funcTypeCode + "_file"; } //得到主表数据列表 @@ -4066,42 +3876,42 @@ public class FileManageService { // 查找页数字段 // todo - Integer quantity = 0,quantityFlag=0; + Integer quantity = 0, quantityFlag = 0; TtableDescription ttableDescription = tableDescriptionMapper.selectTtableDescOne(tableName); List ttableStructDescriptionList = ttableStructDescriptionMapper.selectByTableName(tableName); for (TtableStructDescription ttableStructDescription : ttableStructDescriptionList) { String columnChnName = ttableStructDescription.getColumnChnName(); - if ("页数".equals(columnChnName)){ + if ("页数".equals(columnChnName)) { quantity = StringUtil.formatMapToInt(map0, ttableStructDescription.getColumnName()); quantityFlag = 1; break; } } - if(quantity==null){ - quantity=0; + if (quantity == null) { + quantity = 0; } //得到主表--原文图片数据列表 Map parasMapFile = new HashMap(); parasMapFile.put("tableName", tableNameYuanwen); parasMapFile.put("conditionSql", " rec_id in ( " + zhujianId + " ) and file_status=1 "); - List> dataFile= danganguanliMapper.selectObject(parasMapFile); - int sumFile=0; - for (Map map:dataFile) { + List> dataFile = danganguanliMapper.selectObject(parasMapFile); + int sumFile = 0; + for (Map map : dataFile) { String file_name_server = StringUtil.formatMap(map, "file_name_server"); file_name_server = file_name_server.replaceAll(".jpg", ".pdf"); String file_path = StringUtil.formatMap(map, "file_path"); String file_des = StringUtil.formatMap(map, "file_des"); //String dir = imgUpload + File.separator + file_path + File.separator + file_name_server; - String dir = file_des + File.separator + file_name_server; - int count= PdfFileHelper.getPdfPageCounOrOther(dir); + String dir = file_des + File.separator + file_name_server; + int count = PdfFileHelper.getPdfPageCounOrOther(dir); System.out.println(count); - sumFile=sumFile+count; + sumFile = sumFile + count; } - if (quantity!=sumFile && quantityFlag!=0){ + if (quantity != sumFile && quantityFlag != 0) { //json = AjaxJson.returnExceptionInfo("页数和原文数量是否匹配!"); - json.put("info","页数和原文数量不匹配!"); + json.put("info", "页数和原文数量不匹配!"); } return json; } diff --git a/src/main/java/com/point/strategy/ureport/service/UreportService.java b/src/main/java/com/point/strategy/ureport/service/UreportService.java index e350d89..e59c867 100644 --- a/src/main/java/com/point/strategy/ureport/service/UreportService.java +++ b/src/main/java/com/point/strategy/ureport/service/UreportService.java @@ -202,6 +202,7 @@ public class UreportService { String tarFile = pathName + File.separator+ currentName + ".pdf"; PdfFileHelper.mergePdf(arr, tarFile); + } }else{ //不是封面pdf