LocalSysFileServiceImpl.java 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. package com.xunmei.file.service;
  2. import cn.hutool.core.collection.CollectionUtil;
  3. import cn.hutool.core.date.DateUtil;
  4. import cn.hutool.core.io.FileUtil;
  5. import cn.hutool.core.util.ObjectUtil;
  6. import com.alibaba.fastjson2.JSON;
  7. import com.lowagie.text.*;
  8. import com.lowagie.text.pdf.*;
  9. import com.xunmei.common.core.constant.CacheConstants;
  10. import com.xunmei.common.core.domain.IdName;
  11. import com.xunmei.common.core.domain.registerbook.dto.CoreRegisterBookPdfExportDto;
  12. import com.xunmei.common.core.domain.registerbook.dto.ExportPdfDto;
  13. import com.xunmei.common.core.domain.registerbook.vo.CoreRegisterBookPdfPageVo;
  14. import com.xunmei.common.core.domain.registerbook.vo.PdfLocalFileTempVo;
  15. import com.xunmei.common.core.domain.registerbook.vo.PdfToZipTempVo;
  16. import com.xunmei.common.core.enums.RegisterBookType;
  17. import com.xunmei.common.core.utils.DateHelper;
  18. import com.xunmei.common.core.utils.uuid.UUID;
  19. import com.xunmei.common.redis.utils.RedisUtils;
  20. import com.xunmei.file.utils.FileDownUtils;
  21. import com.xunmei.file.utils.FileUploadUtils;
  22. import com.xunmei.file.utils.PdfUtil;
  23. import com.xunmei.file.vo.FileBase64Vo;
  24. import com.xunmei.file.vo.ItextPdfTableVo;
  25. import com.xunmei.file.vo.PdfFilePathVo;
  26. import com.xunmei.system.api.domain.SafeCheckTaskRegisterBookVo;
  27. import com.xunmei.system.api.vo.SysOrgVO;
  28. import io.netty.util.internal.StringUtil;
  29. import org.apache.commons.lang3.StringUtils;
  30. import org.apache.tools.zip.ZipEntry;
  31. import org.apache.tools.zip.ZipOutputStream;
  32. import org.slf4j.Logger;
  33. import org.slf4j.LoggerFactory;
  34. import org.springframework.beans.factory.annotation.Autowired;
  35. import org.springframework.beans.factory.annotation.Value;
  36. import org.springframework.context.annotation.Primary;
  37. import org.springframework.data.redis.core.BoundValueOperations;
  38. import org.springframework.data.redis.core.RedisTemplate;
  39. import org.springframework.data.redis.core.StringRedisTemplate;
  40. import org.springframework.http.HttpHeaders;
  41. import org.springframework.http.MediaType;
  42. import org.springframework.stereotype.Service;
  43. import org.springframework.web.multipart.MultipartFile;
  44. import javax.servlet.ServletOutputStream;
  45. import javax.servlet.http.HttpServletRequest;
  46. import javax.servlet.http.HttpServletResponse;
  47. import java.io.*;
  48. import java.math.BigDecimal;
  49. import java.net.URLDecoder;
  50. import java.net.URLEncoder;
  51. import java.nio.charset.StandardCharsets;
  52. import java.nio.file.Files;
  53. import java.time.Duration;
  54. import java.util.List;
  55. import java.util.*;
  56. import java.util.concurrent.CountDownLatch;
  57. import java.util.regex.Matcher;
  58. import java.util.regex.Pattern;
  59. import java.util.stream.Collectors;
  60. /**
  61. * 本地文件存储
  62. *
  63. * @author xunmei
  64. */
  65. @Primary
  66. @Service
  67. public class LocalSysFileServiceImpl implements ISysFileService {
  68. private static final Logger log = LoggerFactory.getLogger(LocalSysFileServiceImpl.class);
  69. public static final String TEMP_DIR_NAME = "registerBookPdfBatchExportTempDir";
  70. @Value("${file.path}")
  71. private String localFilePath;
  72. @Value("${file.prefix}")
  73. public String prefix;
  74. @Autowired
  75. private HttpServletRequest request;
  76. @Autowired
  77. private StringRedisTemplate redisTemplate;
  78. private static PdfFilePathVo getLocalFilePath(String localFilePath, String businessType, String fileName) {
  79. fileName = filterPath(fileName);
  80. businessType = filterPath(businessType);
  81. final String path = File.separator + businessType + File.separator + DateUtil.format(new Date(), "yyyy" + File.separator + "MM" + File.separator + "dd" + File.separator);
  82. final File file = new File(localFilePath + path);
  83. if (!file.exists()) {
  84. file.mkdirs();
  85. }
  86. PdfFilePathVo pathVo = new PdfFilePathVo();
  87. pathVo.setAbsolutePath(localFilePath + path + fileName);
  88. pathVo.setRelativePath(path + fileName);
  89. return pathVo;
  90. }
  91. /**
  92. * 修复路径操纵bug
  93. *
  94. * @param param
  95. * @return
  96. */
  97. private static String filterPath(String param) {
  98. Pattern pattern = Pattern.compile("[/\\:*?<>|]");
  99. Matcher matcher = pattern.matcher(param);
  100. param = matcher.replaceAll("");
  101. return param;
  102. }
  103. private static String filterHeader(String param) {
  104. Pattern pattern = Pattern.compile("[/\\:*?<>|=\\r\\n]");
  105. Matcher matcher = pattern.matcher(param);
  106. param = matcher.replaceAll("");
  107. return param;
  108. }
  109. /**
  110. * 本地文件上传接口
  111. *
  112. * @param file 上传的文件
  113. * @return 访问地址
  114. * @throws Exception
  115. */
  116. @Override
  117. public String uploadFile(MultipartFile file) throws Exception {
  118. String name = FileUploadUtils.upload(localFilePath, file);
  119. // String url = domain + localFilePrefix + name;
  120. return name;
  121. }
  122. @Override
  123. public String uploadFile(MultipartFile file, String busType) throws Exception {
  124. String name = FileUploadUtils.upload(localFilePath, file, busType);
  125. // String url = domain + localFilePrefix + name;
  126. return name;
  127. }
  128. @Override
  129. public void downloadFile(HttpServletResponse response, String filePath) {
  130. ByteArrayOutputStream out = null;
  131. try {
  132. filePath = localFilePath + filePath;
  133. filePath = URLDecoder.decode(filePath, "UTF-8");
  134. out = FileDownUtils.downloadFile(filePath);
  135. String fileSuffix = FileDownUtils.getFileSuffix(filePath);
  136. String formFileName = UUID.randomUUID().toString() + fileSuffix;
  137. String userAgent = request.getHeader("User-Agent");
  138. // 针对IE或者以IE为内核的浏览器:
  139. if (StringUtils.isNotEmpty(userAgent) && (userAgent.contains("MSIE") || userAgent.contains("Trident"))) {
  140. formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
  141. } else {
  142. // 非IE浏览器的处理:
  143. formFileName = new String(formFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
  144. }
  145. response.reset();
  146. response.setCharacterEncoding("UTF-8");
  147. response.addHeader("Content-Disposition", "attachment;filename=" + formFileName);
  148. response.addHeader("Content-Length", "" + out.size());
  149. out.writeTo(response.getOutputStream());
  150. response.setContentType("application/octet-stream");
  151. out.flush();
  152. out.close();
  153. } catch (IOException e) {
  154. log.error("文件下载失败! ");
  155. e.printStackTrace();
  156. } finally {
  157. try {
  158. if (out != null) {
  159. out.close();
  160. }
  161. } catch (IOException e) {
  162. e.printStackTrace();
  163. }
  164. }
  165. }
  166. @Override
  167. public void getFileStream(String path, HttpServletResponse response) {
  168. if (ObjectUtil.isEmpty(path)) {
  169. return;
  170. }
  171. if (!path.startsWith(this.localFilePath)) {
  172. path = this.localFilePath + path;
  173. }
  174. try {
  175. File file = new File(path);
  176. FileInputStream inputStream = new FileInputStream(file);
  177. int i = path.lastIndexOf(File.separator);
  178. String fileName = path.substring(i + 1);
  179. fileName = filterHeader(fileName);
  180. // 设置响应头
  181. response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
  182. response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  183. // 将文件流写入响应输出流
  184. byte[] buffer = new byte[1024];
  185. int bytesRead;
  186. while ((bytesRead = inputStream.read(buffer)) != -1) {
  187. response.getOutputStream().write(buffer, 0, bytesRead);
  188. }
  189. inputStream.close();
  190. } catch (Exception e) {
  191. log.error("获取文件内容失败!");
  192. }
  193. }
  194. @Override
  195. public String getRelativePath(String path) {
  196. if (ObjectUtil.isEmpty(path)) {
  197. return null;
  198. }
  199. if (path.startsWith(this.localFilePath)) {
  200. return path.substring(this.localFilePath.length());
  201. }
  202. return path;
  203. }
  204. private void dealHeader(Map<String, Object> dataMap, Document document, BaseFont abf, BaseFont fs) throws
  205. DocumentException {
  206. //处理标题
  207. Paragraph p = new Paragraph("日常履职登记簿", new Font(fs, 20, Font.NORMAL));
  208. p.setAlignment(Paragraph.ALIGN_CENTER);
  209. //段落下空白
  210. p.setSpacingAfter(10f);
  211. document.add(p);
  212. //日期
  213. String blankStr1 = " ";
  214. String blankStr2 = " ";
  215. Paragraph p2 = new Paragraph(dataMap.get("orgName") + blankStr1 + dataMap.get("dateStr") + blankStr2, new Font(abf, 10, Font.NORMAL));
  216. p2.setAlignment(Paragraph.ALIGN_RIGHT);
  217. document.add(p2);
  218. }
  219. @Override
  220. public String generateEduTrainingPdf(Map<String, Object> data) throws Exception {
  221. PdfFilePathVo pathVo = getLocalFilePath(localFilePath, "edu", data.get("fileName").toString());
  222. log.info("开始生成教育培训登记簿,当前绝对地址为:{}", pathVo.getAbsolutePath());
  223. final ItextPdfTableVo pdfTableVo = PdfUtil.createTable(pathVo.getAbsolutePath(), 6, 10);
  224. final Document document = pdfTableVo.getDocument();
  225. final PdfWriter writer = pdfTableVo.getWriter();
  226. final PdfPTable table = pdfTableVo.getTable();
  227. final BaseFont fs = pdfTableVo.getFs();
  228. final Font tableFont = pdfTableVo.getTableFont();
  229. PdfUtil.dealHeader(document, fs, "学 习 教 育 记 录", 24);
  230. PdfUtil.dealEduBody(document, table, tableFont, data);
  231. document.close();
  232. writer.close();
  233. log.info("教育培训登记簿生成结束,当前绝对地址为:{}", pathVo.getAbsolutePath());
  234. //此处返回 /statics/edu/xxx.pdf
  235. return this.prefix + pathVo.getRelativePath();
  236. }
  237. @Override
  238. public String generateResumptionPdf(Map<String, Object> data) throws Exception {
  239. PdfFilePathVo pathVo = getLocalFilePath(localFilePath, "resumption", data.get("fileName").toString());
  240. log.info("开始生成履职登记簿,当前绝对地址为:{}", pathVo.getAbsolutePath());
  241. Document document = new Document();
  242. PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pathVo.getAbsolutePath()));
  243. document.open();
  244. // 使用语言包字体
  245. BaseFont abf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  246. // 外部字体
  247. BaseFont fs = BaseFont.createFont("/fonts/msyh.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  248. Font tableFont = new Font(fs, 12, Font.NORMAL);
  249. PdfPTable table = new PdfPTable(8);
  250. table.setSpacingBefore(16f);
  251. this.dealHeader(data, document, abf, fs);
  252. PdfUtil.dealResumptionBody(document, table, tableFont, data);
  253. document.close();
  254. writer.close();
  255. log.info("履职登记簿生成结束,当前绝对地址为:{}", pathVo.getAbsolutePath());
  256. //此处返回 /statics/edu/xxx.pdf
  257. return this.prefix + pathVo.getRelativePath();
  258. }
  259. @Override
  260. public String generateSafeCheckPdf(SafeCheckTaskRegisterBookVo data) throws Exception {
  261. PdfFilePathVo pathVo = getLocalFilePath(localFilePath, "safeCheck", data.getDest());
  262. log.info("开始生成安全检查登记簿,当前绝对地址为:{}", pathVo.getAbsolutePath());
  263. final ItextPdfTableVo pdfTableVo = PdfUtil.createTable(pathVo.getAbsolutePath(), 46, 7);
  264. final Document document = pdfTableVo.getDocument();
  265. final PdfWriter writer = pdfTableVo.getWriter();
  266. final PdfPTable table = pdfTableVo.getTable();
  267. final BaseFont fs = pdfTableVo.getFs();
  268. final Font tableFont = pdfTableVo.getTableFont();
  269. Font font = new Font(fs, 9, Font.NORMAL);
  270. PdfUtil.dealHeader(document, fs, data.getTaskTitle(), 14);
  271. //日期
  272. String orgName = "被查支行: " + data.getOrgName();
  273. String checkUser = "检查人签名: " + data.getCheckUserInfo();
  274. String dateStr = data.getDateStr();
  275. PdfPCell orgCell = new PdfPCell(new Phrase(orgName, font));
  276. orgCell.setColspan(16);
  277. orgCell.setRowspan(1);
  278. orgCell.setBorder(Rectangle.NO_BORDER);
  279. orgCell.setHorizontalAlignment(Element.ALIGN_LEFT);
  280. PdfPCell checkUserCell = new PdfPCell(new Phrase(checkUser, font));
  281. checkUserCell.setColspan(20);
  282. checkUserCell.setRowspan(1);
  283. checkUserCell.setBorder(Rectangle.NO_BORDER);
  284. checkUserCell.setHorizontalAlignment(Element.ALIGN_CENTER);
  285. PdfPCell dateStrCell = new PdfPCell(new Phrase(dateStr, font));
  286. dateStrCell.setColspan(10);
  287. dateStrCell.setRowspan(1);
  288. dateStrCell.setBorder(Rectangle.NO_BORDER);
  289. dateStrCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
  290. table.addCell(orgCell);
  291. table.addCell(checkUserCell);
  292. table.addCell(dateStrCell);
  293. Font titleFont = new Font(fs, 8, Font.NORMAL);
  294. PdfUtil.dealSafeCheckPBody(document, table, tableFont, titleFont, data.getCheckDatas());
  295. document.close();
  296. writer.close();
  297. log.info("安全检查登记簿生成结束,当前绝对地址为:{}", pathVo.getAbsolutePath());
  298. //此处返回 /statics/edu/xxx.pdf
  299. return this.prefix + pathVo.getRelativePath();
  300. }
  301. @Override
  302. public String generateDrillPdf(Map<String, Object> data) throws Exception {
  303. PdfFilePathVo pathVo = getLocalFilePath(localFilePath, "drill", data.get("fileName").toString());
  304. log.info("开始生成预案演练登记簿,当前绝对地址为:{}", pathVo.getAbsolutePath());
  305. final ItextPdfTableVo pdfTableVo = PdfUtil.createTable(pathVo.getAbsolutePath(), 6, 10);
  306. final Document document = pdfTableVo.getDocument();
  307. final PdfWriter writer = pdfTableVo.getWriter();
  308. final PdfPTable table = pdfTableVo.getTable();
  309. final BaseFont fs = pdfTableVo.getFs();
  310. final Font tableFont = pdfTableVo.getTableFont();
  311. PdfUtil.dealHeader(document, fs, "预 案 演 练 记 录", 24);
  312. PdfUtil.dealDrillBody(document, table, tableFont, data);
  313. document.close();
  314. writer.close();
  315. log.info("预案演练登记簿生成结束,当前绝对地址为:{}", pathVo.getAbsolutePath());
  316. //此处返回 /statics/edu/xxx.pdf
  317. return this.prefix + pathVo.getRelativePath();
  318. }
  319. @Override
  320. public String uploadFileBase64(FileBase64Vo file) throws Exception {
  321. String filePath = FileUploadUtils.uploadBase64(localFilePath, file);
  322. return filePath;
  323. }
  324. /**
  325. * 履职转pdf
  326. *
  327. * @param dest
  328. * @throws IOException
  329. * @throws DocumentException
  330. */
  331. public void dataToPdf(String dest) throws IOException, DocumentException {
  332. Document document = new Document();
  333. PdfWriter.getInstance(document, new FileOutputStream(dest));
  334. document.open();
  335. // 使用语言包字体
  336. BaseFont abf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  337. //字体
  338. Font font = new Font(abf, 8);
  339. //段落
  340. Paragraph p = new Paragraph("测试结算单", new Font(abf, 12, Font.BOLD));
  341. p.setAlignment(Paragraph.ALIGN_CENTER);
  342. document.add(p);
  343. //表格
  344. PdfPTable table = new PdfPTable(8);//numcolumns:列数
  345. table.setSpacingBefore(16f);//表格与上面段落的空隙
  346. //表格列创建并赋值
  347. PdfPCell cell = new PdfPCell(new Phrase("单位名称:测试有限公司", font));
  348. cell.setHorizontalAlignment(Element.ALIGN_LEFT);//居中
  349. cell.disableBorderSide(13);//去除左右上边框,保留下边框
  350. cell.setColspan(4);//合并列数
  351. table.addCell(cell);
  352. cell = new PdfPCell(new Phrase("日期:2020-06-05", font));
  353. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  354. cell.disableBorderSide(13);
  355. cell.setColspan(3);
  356. table.addCell(cell);
  357. cell = new PdfPCell(new Phrase("单位(元)", font));
  358. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  359. cell.disableBorderSide(13);
  360. cell.setColspan(1);
  361. table.addCell(cell);
  362. //首行
  363. cell = new PdfPCell(new Phrase("期间", font));
  364. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  365. cell.setColspan(2);
  366. table.addCell(cell);
  367. cell = new PdfPCell(new Phrase("月份", font));
  368. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  369. table.addCell(cell);
  370. cell = new PdfPCell(new Phrase("分类", font));
  371. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  372. table.addCell(cell);
  373. cell = new PdfPCell(new Phrase("年利率", font));
  374. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  375. table.addCell(cell);
  376. cell = new PdfPCell(new Phrase("日利率", font));
  377. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  378. table.addCell(cell);
  379. cell = new PdfPCell(new Phrase("基数", font));
  380. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  381. table.addCell(cell);
  382. cell = new PdfPCell(new Phrase("利息", font));
  383. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  384. table.addCell(cell);
  385. cell = new PdfPCell(new Phrase("起始日:2020-03-26\n" +
  386. "结束日:2020-04-25", font));
  387. cell.setPadding(16f);
  388. cell.setVerticalAlignment(Element.ALIGN_CENTER);
  389. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  390. cell.setRowspan(3);
  391. cell.setColspan(2);
  392. table.addCell(cell);
  393. cell = new PdfPCell(new Phrase("4", font));
  394. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  395. table.addCell(cell);
  396. cell = new PdfPCell(new Phrase("资金", font));
  397. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  398. table.addCell(cell);
  399. cell = new PdfPCell(new Phrase("1.10%", font));
  400. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  401. table.addCell(cell);
  402. cell = new PdfPCell(new Phrase("0.000031", font));
  403. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  404. table.addCell(cell);
  405. cell = new PdfPCell(new Phrase("10598164.91", font));
  406. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  407. table.addCell(cell);
  408. cell = new PdfPCell(new Phrase("325.01", font));
  409. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  410. table.addCell(cell);
  411. cell = new PdfPCell(new Phrase("4", font));
  412. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  413. table.addCell(cell);
  414. cell = new PdfPCell(new Phrase("资金", font));
  415. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  416. table.addCell(cell);
  417. cell = new PdfPCell(new Phrase("1.10%", font));
  418. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  419. table.addCell(cell);
  420. cell = new PdfPCell(new Phrase("0.000031", font));
  421. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  422. table.addCell(cell);
  423. cell = new PdfPCell(new Phrase("-", font));
  424. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  425. table.addCell(cell);
  426. cell = new PdfPCell(new Phrase("-", font));
  427. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  428. table.addCell(cell);
  429. cell = new PdfPCell(new Phrase("4", font));
  430. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  431. table.addCell(cell);
  432. cell = new PdfPCell(new Phrase("资金", font));
  433. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  434. table.addCell(cell);
  435. cell = new PdfPCell(new Phrase("1.10%", font));
  436. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  437. table.addCell(cell);
  438. cell = new PdfPCell(new Phrase("0.000031", font));
  439. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  440. table.addCell(cell);
  441. cell = new PdfPCell(new Phrase("-", font));
  442. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  443. table.addCell(cell);
  444. cell = new PdfPCell(new Phrase("-", font));
  445. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  446. table.addCell(cell);
  447. cell = new PdfPCell(new Phrase("合计", font));
  448. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  449. cell.setColspan(7);
  450. table.addCell(cell);
  451. cell = new PdfPCell(new Phrase("325.01", font));
  452. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  453. table.addCell(cell);
  454. cell = new PdfPCell(new Phrase("会计制单:", font));
  455. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  456. cell.disableBorderSide(14);
  457. cell.setColspan(4);
  458. table.addCell(cell);
  459. cell = new PdfPCell(new Phrase("复核:", font));
  460. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  461. cell.disableBorderSide(14);
  462. cell.setColspan(4);
  463. table.addCell(cell);
  464. table.setSpacingBefore(16f);
  465. document.add(table);
  466. //下一页
  467. document.newPage();
  468. //段落
  469. Paragraph p1 = new Paragraph("下一页测试结算单", new Font(abf, 12, Font.BOLD));
  470. p1.setAlignment(Paragraph.ALIGN_CENTER);
  471. document.add(p1);
  472. //表格
  473. table = new PdfPTable(8);//numcolumns:列数
  474. table.setSpacingBefore(16f);//表格与上面段落的空隙
  475. //表格列创建并赋值
  476. cell = new PdfPCell(new Phrase("单位名称:测试有限公司", font));
  477. cell.setHorizontalAlignment(Element.ALIGN_LEFT);//居中
  478. cell.disableBorderSide(13);//去除左右上边框,保留下边框
  479. cell.setColspan(4);//合并列数
  480. table.addCell(cell);
  481. cell = new PdfPCell(new Phrase("日期:2020-06-05", font));
  482. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  483. cell.disableBorderSide(13);
  484. cell.setColspan(3);
  485. table.addCell(cell);
  486. cell = new PdfPCell(new Phrase("单位(元)", font));
  487. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  488. cell.disableBorderSide(13);
  489. cell.setColspan(1);
  490. table.addCell(cell);
  491. //首行
  492. cell = new PdfPCell(new Phrase("期间", font));
  493. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  494. cell.setColspan(2);
  495. table.addCell(cell);
  496. cell = new PdfPCell(new Phrase("月份", font));
  497. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  498. table.addCell(cell);
  499. cell = new PdfPCell(new Phrase("分类", font));
  500. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  501. table.addCell(cell);
  502. cell = new PdfPCell(new Phrase("年利率", font));
  503. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  504. table.addCell(cell);
  505. cell = new PdfPCell(new Phrase("日利率", font));
  506. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  507. table.addCell(cell);
  508. cell = new PdfPCell(new Phrase("基数", font));
  509. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  510. table.addCell(cell);
  511. cell = new PdfPCell(new Phrase("利息", font));
  512. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  513. table.addCell(cell);
  514. cell = new PdfPCell(new Phrase("起始日:2020-04-26\n" +
  515. "结束日:2020-05-25", font));
  516. cell.setPadding(16f);
  517. cell.setVerticalAlignment(Element.ALIGN_CENTER);
  518. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  519. cell.setColspan(2);
  520. table.addCell(cell);
  521. cell = new PdfPCell(new Phrase("4", font));
  522. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  523. table.addCell(cell);
  524. cell = new PdfPCell(new Phrase("资金", font));
  525. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  526. table.addCell(cell);
  527. cell = new PdfPCell(new Phrase("1.10%", font));
  528. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  529. table.addCell(cell);
  530. cell = new PdfPCell(new Phrase("0.000031", font));
  531. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  532. table.addCell(cell);
  533. cell = new PdfPCell(new Phrase("10598164.91", font));
  534. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  535. table.addCell(cell);
  536. cell = new PdfPCell(new Phrase("325.01", font));
  537. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  538. table.addCell(cell);
  539. cell = new PdfPCell(new Phrase("合计", font));
  540. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  541. cell.setColspan(7);
  542. table.addCell(cell);
  543. cell = new PdfPCell(new Phrase("325.01", font));
  544. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  545. table.addCell(cell);
  546. cell = new PdfPCell(new Phrase("会计制单:", font));
  547. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  548. cell.disableBorderSide(14);
  549. cell.setColspan(4);
  550. table.addCell(cell);
  551. cell = new PdfPCell(new Phrase("复核:", font));
  552. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
  553. cell.disableBorderSide(14);
  554. cell.setColspan(4);
  555. table.addCell(cell);
  556. table.setSpacingBefore(16f);
  557. document.add(table);
  558. document.close();
  559. }
  560. @Override
  561. public String absolutePath(String path) {
  562. if (ObjectUtil.isEmpty(path)) {
  563. return StringUtil.EMPTY_STRING;
  564. }
  565. if (path.startsWith(this.localFilePath)) {
  566. return path;
  567. }
  568. if (path.startsWith(this.prefix)) {
  569. return this.localFilePath + path.substring(this.prefix.length());
  570. }
  571. return StringUtil.EMPTY_STRING;
  572. }
  573. @Override
  574. public InputStream getFileStream(String path) throws IOException {
  575. String absolutePath = this.absolutePath(path);
  576. File file = new File(absolutePath);
  577. return Files.newInputStream(file.toPath());
  578. }
  579. @Override
  580. public void registerBookCompressPdf(ExportPdfDto pdfDto, HttpServletResponse response) throws IOException {
  581. final List<CoreRegisterBookPdfPageVo> registerBookPdfList = pdfDto.getRegisterBookPdfList();
  582. try {
  583. String zipName = URLEncoder.encode(pdfDto.getFileName() + DateHelper.getDateString(new Date()) + ".zip", "UTF-8");
  584. final CountDownLatch count = new CountDownLatch(registerBookPdfList.size());
  585. ServletOutputStream outputStream = response.getOutputStream();
  586. ZipOutputStream zos = new ZipOutputStream(outputStream);
  587. response.setContentType("application/octet-stream");
  588. response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
  589. List<PdfToZipTempVo> pdfToZipTempVoList = registerBookPdfList.parallelStream().map(pdf -> {
  590. return resolve(pdf, count);
  591. }).filter(Objects::nonNull)
  592. .collect(Collectors.toList());
  593. count.await();
  594. pdfToZipTempVoList.removeIf(pdfToZipTempVo -> !FileUtil.exist(pdfToZipTempVo.getFile()));
  595. log.info("登记簿全部下载完成,开始压缩文件,数量:{}", pdfToZipTempVoList.size());
  596. for (PdfToZipTempVo tempVo : pdfToZipTempVoList) {
  597. log.info("当前开始处理第{}个文件 ", pdfToZipTempVoList.indexOf(tempVo) + 1);
  598. deal(zos, tempVo);
  599. }
  600. zos.flush();
  601. zos.close();
  602. outputStream.close();
  603. log.info("登记簿批量导出压缩文件完成,文件数量:{}", pdfToZipTempVoList.size());
  604. } catch (Throwable e) {
  605. String errMsg = String.format("登记簿导出失败:%s", e);
  606. log.error(errMsg);
  607. } finally {
  608. final File temp = new File(TEMP_DIR_NAME);
  609. if (temp.exists()) {
  610. FileUtil.del(temp);
  611. log.info("临时目录已删除");
  612. }
  613. }
  614. }
  615. public PdfToZipTempVo resolve(CoreRegisterBookPdfPageVo pdf, CountDownLatch count) {
  616. final File temp = new File(TEMP_DIR_NAME);
  617. if (!temp.exists()) {
  618. temp.mkdirs();
  619. }
  620. InputStream inputStream;
  621. try {
  622. inputStream = getFileStream(pdf.getFileUrl());
  623. if (ObjectUtil.isEmpty(inputStream)) {
  624. log.error("登记簿导出失败,文件不存在,文件名:{}", pdf.getFileUrl());
  625. return null;
  626. }
  627. final String pdfFileName = pdf.getFileName();
  628. //pdfFileName==null的时候在下面会报错此处加个判断,要处理问题还需要在问题源头除处理
  629. // registerBookPdfBatchExportTempDir (Is a directory)
  630. if (StringUtils.isEmpty(pdfFileName)) {
  631. return null;
  632. }
  633. final PdfToZipTempVo tempVo = new PdfToZipTempVo();
  634. //tempVo.setBytes(bytes);
  635. tempVo.setFileName(pdfFileName);
  636. tempVo.setOrgId(pdf.getOrgId());
  637. tempVo.setOrgName(pdf.getOrgName());
  638. tempVo.setRegisterBookType(RegisterBookType.getEnums(pdf.getRegisterBookType()));
  639. final File file = new File(temp + File.separator + pdfFileName);
  640. final FileOutputStream outputStream = new FileOutputStream(file);
  641. byte[] buffer = new byte[4096];
  642. int len;
  643. while ((len = inputStream.read(buffer)) > 0) {
  644. outputStream.write(buffer, 0, len);
  645. }
  646. outputStream.close();
  647. inputStream.close();
  648. tempVo.setFile(file);
  649. final List<IdName<Long, String>> idNameList = pdf.getOrgList();
  650. if (ObjectUtil.isEmpty(idNameList)) {
  651. tempVo.setEntryName(File.separator + RegisterBookType.getEnums(pdf.getRegisterBookType()).getText() + File.separator + pdfFileName);
  652. return tempVo;
  653. }
  654. StringJoiner stringJoiner = new StringJoiner(File.separator);
  655. for (IdName<Long, String> org : idNameList) {
  656. stringJoiner.add(org.getName());
  657. if (idNameList.lastIndexOf(org) == idNameList.size() - 1) {
  658. stringJoiner.add(RegisterBookType.getEnums(pdf.getRegisterBookType()).getText() + File.separator + pdfFileName);
  659. }
  660. }
  661. tempVo.setEntryName(stringJoiner.toString());
  662. return tempVo;
  663. } catch (Exception e) {
  664. log.error("读取文件失败", e);
  665. return null;
  666. } finally {
  667. count.countDown();
  668. }
  669. }
  670. public void deal(ZipOutputStream zos, PdfToZipTempVo zipTempVo) throws Throwable {
  671. zos.setEncoding("GBK");
  672. FileInputStream fileInputStream = new FileInputStream(zipTempVo.getFile());
  673. zos.putNextEntry(new ZipEntry(zipTempVo.getEntryName()));
  674. byte[] buffer = new byte[4096];
  675. int len;
  676. while ((len = fileInputStream.read(buffer)) > 0) {
  677. zos.write(buffer, 0, len);
  678. }
  679. zos.closeEntry();
  680. fileInputStream.close();
  681. }
  682. private List<SysOrgVO> getChildrenList(Long orgId) {
  683. List<SysOrgVO> cacheList = RedisUtils.getCacheList(CacheConstants.ORG_CACHE_LIST_KEY);
  684. return cacheList.stream()
  685. .filter(org -> ObjectUtil.equal(org.getParentId(), orgId))
  686. .collect(Collectors.toList());
  687. }
  688. private SysOrgVO getCurOrg(Long orgId) {
  689. List<SysOrgVO> cacheList = RedisUtils.getCacheList(CacheConstants.ORG_CACHE_LIST_KEY);
  690. return cacheList.stream()
  691. .filter(org -> ObjectUtil.equal(org.getId(), orgId))
  692. .findFirst().get();
  693. }
  694. @Override
  695. public void cutFileCompress(CoreRegisterBookPdfExportDto pdfDto) {
  696. SysOrgVO org = getCurOrg(pdfDto.getOrgId());
  697. Date date = new Date();
  698. String fileName = pdfDto.getIsRegisterBookPage() ? org.getName() + "_登记簿_" : org.getName() + "_数据报表_";
  699. //判断需要分几片导出
  700. List<List<CoreRegisterBookPdfPageVo>> lists = checkSubList(pdfDto);
  701. int num = 1;
  702. try {
  703. for (List<CoreRegisterBookPdfPageVo> list : lists) {
  704. CountDownLatch count = new CountDownLatch(list.size());
  705. String zipName = null;
  706. String str = lists.size() == 1 ? "" : "_part_" + num;
  707. String fileNameStr = fileName + DateHelper.getDateString(new Date()) + str;
  708. zipName = URLEncoder.encode(fileNameStr + ".zip", "UTF-8");
  709. List<PdfToZipTempVo> pdfToZipTempVoList = list.parallelStream().map(pdf -> {
  710. return resolve(pdf, count);
  711. }).filter(Objects::nonNull)
  712. .collect(Collectors.toList());
  713. pdfToZipTempVoList.removeIf(pdfToZipTempVo -> !FileUtil.exist(pdfToZipTempVo.getFile()));
  714. log.info("登记簿全部下载完成,开始压缩文件,数量:{}", pdfToZipTempVoList.size());
  715. String encodedFileName = URLEncoder.encode(CacheConstants.REGISTER_PDF_FILE_KEY + DateHelper.getDateString(date) + str + ".zip", "UTF-8");
  716. String filePath = this.localFilePath + File.separator + encodedFileName;
  717. FileOutputStream fos = new FileOutputStream(filePath);
  718. ZipOutputStream zos = new ZipOutputStream(fos);
  719. long fileSize = 0L;
  720. for (PdfToZipTempVo tempVo : pdfToZipTempVoList) {
  721. fileSize += tempVo.getFile().length();
  722. log.info("当前开始处理第{}个文件 ", pdfToZipTempVoList.indexOf(tempVo) + 1);
  723. deal(zos, tempVo);
  724. }
  725. zos.flush();
  726. fos.flush();
  727. zos.close();
  728. fos.close();
  729. num++;
  730. saveFileDataToRedis(org, date, zipName, filePath, fileSize, pdfDto);
  731. }
  732. } catch (Throwable e) {
  733. throw new RuntimeException(e);
  734. } finally {
  735. File file = new File(TEMP_DIR_NAME);
  736. if (file.exists()) {
  737. FileUtil.del(file);
  738. }
  739. }
  740. }
  741. private void saveFileDataToRedis(SysOrgVO org, Date date, String zipName, String localFileName, long fileSize, CoreRegisterBookPdfExportDto pdfDto) throws UnsupportedEncodingException {
  742. PdfLocalFileTempVo pdfLocalFileTempVo = new PdfLocalFileTempVo();
  743. pdfLocalFileTempVo.setOrgId(pdfDto.getOrgId());
  744. pdfLocalFileTempVo.setOrgName(org.getName());
  745. pdfLocalFileTempVo.setOrgPath(org.getPath());
  746. pdfLocalFileTempVo.setLocalFileName(localFileName);
  747. pdfLocalFileTempVo.setZipName(URLDecoder.decode(zipName, "UTF-8"));
  748. pdfLocalFileTempVo.setFileSize(changeUnit(fileSize));
  749. pdfLocalFileTempVo.setDownLoadTime(DateUtil.format(date, "yyyy-MM-dd HH:mm:ss"));
  750. pdfLocalFileTempVo.setIsRegisterBookPage(pdfDto.getIsRegisterBookPage());
  751. pdfLocalFileTempVo.setCreateTime(new Date());
  752. //此处localFileName 为文件的绝对路径,存在redis延迟队列中,一个小时后删除文件
  753. localFileName = localFileName.replace(this.localFilePath + File.separator, "");
  754. //此处localFileName 为文件名称,存入redis中,用于页面展示文件名称,下载
  755. //RedisUtils.setCacheObject(URLDecoder.decode(localFileName, "UTF-8"), JSON.toJSONString(pdfLocalFileTempVo),true);
  756. final BoundValueOperations ops = redisTemplate.boundValueOps(URLDecoder.decode(localFileName, "UTF-8"));
  757. ops.set(JSON.toJSONString(pdfLocalFileTempVo));
  758. ops.expireAt(DateUtil.endOfDay(new Date()));
  759. }
  760. private List<List<CoreRegisterBookPdfPageVo>> checkSubList(CoreRegisterBookPdfExportDto pdfDto) {
  761. List<List<CoreRegisterBookPdfPageVo>> list = new ArrayList<>();
  762. List<CoreRegisterBookPdfPageVo> registerBookPdfList = pdfDto.getDataList();
  763. if (CollectionUtil.isEmpty(registerBookPdfList)) {
  764. throw new RuntimeException("暂无可下载数据!");
  765. }
  766. //小于3000条直接导出
  767. if (registerBookPdfList.size() < 3000) {
  768. list.add(registerBookPdfList);
  769. return list;
  770. }
  771. List<SysOrgVO> orgList = getChildrenList(pdfDto.getOrgId());
  772. //大于3000条需要分片
  773. return splitList(registerBookPdfList, orgList, 3000);
  774. }
  775. public static List<List<CoreRegisterBookPdfPageVo>> splitList(List<CoreRegisterBookPdfPageVo> list, List<SysOrgVO> orgList, int size) {
  776. // 根据机构分组
  777. List<List<CoreRegisterBookPdfPageVo>> collect = orgList.stream().map(org -> {
  778. List<CoreRegisterBookPdfPageVo> arrayList = new ArrayList<>();
  779. for (CoreRegisterBookPdfPageVo pdf : list) {
  780. if (pdf.getOrgPath().startsWith(org.getPath())) {
  781. arrayList.add(pdf);
  782. }
  783. }
  784. return arrayList;
  785. }).filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
  786. // 合并不满3000的数组
  787. List<List<CoreRegisterBookPdfPageVo>> merged = new LinkedList<>();
  788. List<CoreRegisterBookPdfPageVo> current = new ArrayList<>();
  789. for (List<CoreRegisterBookPdfPageVo> group : collect) {
  790. if (group.size() >= size) {
  791. merged.add(group);
  792. } else {
  793. current.addAll(group);
  794. if (current.size() >= size) {
  795. merged.add(current);
  796. current = new ArrayList<>();
  797. }
  798. }
  799. }
  800. if (!current.isEmpty()) {
  801. merged.add(current);
  802. }
  803. return merged;
  804. //return merged.stream().limit(size).collect(Collectors.toList());
  805. }
  806. public String changeUnit(Long fileSize) {
  807. if (fileSize == null || fileSize == 0) {
  808. return "0";
  809. }
  810. //将fileSize转换为MB,保留整数
  811. BigDecimal fileSizeMB = new BigDecimal(fileSize).divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP);
  812. return fileSizeMB.toString();
  813. }
  814. @Override
  815. public void deletedZipFile() {
  816. final File dir = new File(this.localFilePath);
  817. final File[] files = dir.listFiles();
  818. if (ObjectUtil.isNull(files) || ObjectUtil.isEmpty(files)) {
  819. return;
  820. }
  821. Arrays.stream(files)
  822. .filter(file -> file.getName().startsWith(CacheConstants.REGISTER_PDF_FILE_KEY))
  823. .filter(file->file.getName().endsWith(".zip"))
  824. .forEach(FileUtil::del);
  825. }
  826. }