fei
5 小时以前 bcb1d905904fd43034f7c95077336e5cb849eff1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
package com.ruoyi.web.controller.archive;
 
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.aspose.cells.PdfCompliance;
import com.aspose.words.License;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deepoove.poi.XWPFTemplate;
import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfPCell;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.*;
import com.ruoyi.domain.ArchiveProjectName;
import com.ruoyi.domain.ArchiveRecords;
import com.ruoyi.domain.DocumentMaterials;
import com.ruoyi.domain.vo.*;
import com.ruoyi.service.IArchiveProjectNameService;
import com.ruoyi.service.IArchiveRecordsService;
import com.ruoyi.service.IDocumentMaterialsService;
import com.ruoyi.service.impl.BarcodeService;
import com.ruoyi.service.impl.pdfGenerateService;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import org.apache.commons.imaging.ImageInfo;
import org.apache.commons.imaging.Imaging;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
// 导入ByteArrayOutputStream用于临时存储PDF数据
import java.io.ByteArrayOutputStream;
 
@RestController
@RequestMapping("/system/archiveAllExport")
public class archiveAllExportController {
    // 存储当天导出序号的Map,键为日期(yyyyMMdd),值为当前序号
    private static Map<String, Integer> dailySequenceMap = new ConcurrentHashMap<>();
 
    @Autowired
    private pdfGenerateService pdfGenerateService;
    @Autowired
    private BarcodeService barcodeService;
    @Autowired
    private IDocumentMaterialsService documentMaterialsService;
    @Autowired
    private IArchiveProjectNameService iArchiveProjectNameService;
    @Autowired
    private IArchiveRecordsService iArchiveRecordsService;
 
    // 用于生成当天导出序号的方法
    private String generateDailySequence(String date) {
        // 使用synchronized确保线程安全
        synchronized (dailySequenceMap) {
            // 获取当前日期的序号,如果不存在则初始化为0
            int sequence = dailySequenceMap.getOrDefault(date, 0);
            // 序号递增
            sequence++;
            // 更新Map中的序号
            dailySequenceMap.put(date, sequence);
            // 格式化为三位字符串,不足三位补前导零
            return String.format("%03d", sequence);
        }
    }
 
    public  boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = null;
 
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            org.springframework.core.io.Resource[] resources = resolver.getResources("classpath:words.xml");
            is = resources[0].getInputStream();
            // ��Ŀ��lincense.xml��·��
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 
    public  boolean getLicenseExcel() {
        boolean result = false;
        InputStream is = null;
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            org.springframework.core.io.Resource[] resources = resolver.getResources("classpath:license.xml");
            is = resources[0].getInputStream();
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
 
 
 
 
    /**
     * 将Excel指定子sheet转换为PDF并下载
     * @param response 响应对象
     * @param excelPath Excel文件路径
     * @param sheetName 子sheet名称
     * @throws Exception 异常信息
     */
    @PostMapping("/exportSheetToPdf")
    public void exportSheetToPdf(HttpServletResponse response, String excelPath, String sheetName) throws Exception {
        // 设置响应头
        response.setContentType(MediaType.APPLICATION_PDF_VALUE);
        response.setHeader("Content-Disposition", "attachment; filename=sheet.pdf");
 
        try {
            // 使用Aspose.Cells读取Excel文件
            com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(excelPath);
 
            // 获取指定名称的子sheet
            com.aspose.cells.Worksheet sheet = wb.getWorksheets().get(sheetName);
 
            // 如果需要获取索引方式的子sheet,可以使用以下代码
            // com.aspose.cells.Worksheet sheet = wb.getWorksheets().get(0); // 获取第一个sheet
 
            // 创建一个新的Workbook,只包含指定的sheet
            com.aspose.cells.Workbook newWorkbook = new com.aspose.cells.Workbook();
            newWorkbook.getWorksheets().clear();
            newWorkbook.getWorksheets().addCopy(sheet.getName());
 
            // 将Excel转换为PDF字节数组
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
            newWorkbook.save(baos, com.aspose.cells.SaveFormat.PDF);
            byte[] pdfBytes = baos.toByteArray();
 
            // 将PDF输出到响应流
            try (ServletOutputStream os = response.getOutputStream()) {
                os.write(pdfBytes);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
 
    /**
     * 将Excel所有子sheet转换为PDF并打包下载
     * @param response 响应对象
     * @param excelPath Excel文件路径
     * @throws Exception 异常信息
     */
    @PostMapping("/exportAllSheetsToPdf")
    public void exportAllSheetsToPdf(HttpServletResponse response, String excelPath) throws Exception {
        // 设置响应头
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=all_sheets.zip");
 
        try (ServletOutputStream os = response.getOutputStream();
             ZipOutputStream zos = new ZipOutputStream(os)) {
 
            // 使用Aspose.Cells读取Excel文件
            com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(excelPath);
 
            // 获取所有sheet
            com.aspose.cells.WorksheetCollection sheets = wb.getWorksheets();
 
            // 遍历所有sheet
            for (int i = 0; i < sheets.getCount(); i++) {
                com.aspose.cells.Worksheet sheet = sheets.get(i);
                String sheetName = sheet.getName();
 
                // 创建一个新的Workbook,只包含当前sheet
                com.aspose.cells.Workbook newWorkbook = new com.aspose.cells.Workbook();
                newWorkbook.getWorksheets().clear();
                newWorkbook.getWorksheets().addCopy(sheet.getName());
 
                // 创建临时字节输出流
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
                // 将新的Workbook保存为PDF到临时流
                newWorkbook.save(baos, com.aspose.cells.SaveFormat.PDF);
                byte[] pdfBytes = baos.toByteArray();
 
                // 获取PDF总页数
 
                // 将PDF添加到ZIP文件
                ZipEntry entry = new ZipEntry(sheetName + ".pdf");
                zos.putNextEntry(entry);
                zos.write(pdfBytes);
                zos.closeEntry();
 
                System.out.println("Excel子sheet \"" + sheetName + "\" 转换为PDF成功");
            }
 
            System.out.println("Excel所有子sheet转换为PDF并打包成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
 
 
        if (!getLicense()) {
            return;
        }
 
        try {
 
            // 获取 Word 模板所在路径
            String filepath = "09-备考表.docx";
            // 通过 XWPFTemplate 编译文件并渲染数据到模板中
            XWPFTemplate template = XWPFTemplate.compile(filepath).render(
                    new HashMap<String, Object>(){{
                        put("pages", 67);
 
                    }});
 
            String renderedDocPath = "rendered_output.docx";
            File renderedFile = new File(renderedDocPath);
 
 
 
            try {
                // 将完成数据渲染的文档写出
                template.writeAndClose(new FileOutputStream(renderedFile));
            } catch (IOException e) {
                e.printStackTrace();
            }
 
 
            File file = new File("test1.pdf");
            FileOutputStream os = new FileOutputStream(file);
            com.aspose.words.Document doc = new com.aspose.words.Document("rendered_output.docx");
 
            doc.save(os, com.aspose.words.SaveFormat.PDF);//ȫ��֧��DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF �໥ת��
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
 
        if (!getLicenseExcel()) {
            System.out.println("授权失败");
            return ;
        }
        String inpath= "案卷封面.xls";
        long old = System.currentTimeMillis();
 
        // 设置响应头
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=import_template.pdf");
 
        try {
            // 读取Excel文件
            com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(inpath);
 
            // 获取需要导出的sheet(索引从0开始)
            int targetSheetIndex = 1;
            com.aspose.cells.Worksheet targetSheet = wb.getWorksheets().get(targetSheetIndex);
            targetSheet.autoFitRows(true);
            System.out.println("当前sheet名称:" + targetSheet.getName());
            System.out.println("当前sheet索引:" + targetSheet.getIndex());
 
            // 隐藏所有其他工作表
            for (int i = 0; i < wb.getWorksheets().getCount(); i++) {
                if (i != targetSheetIndex) {
                    wb.getWorksheets().get(i).setVisible(false);
                }
            }
 
            // 设置活动工作表为目标工作表
            wb.getWorksheets().setActiveSheetIndex(targetSheetIndex);
 
            // 创建PDF保存选项
            com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
 
            // 设置页面类型为A4
 
 
            // 确保所有列在一页上
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
 
            // 设置打印页面类型为默认
            pdfSaveOptions.setCompliance(PdfCompliance.PDF_A_1_B); // 设置 PDF 兼容性标准
 
            // 直接将原始工作簿保存为PDF(只包含可见的工作表)
            wb.save(response.getOutputStream(), pdfSaveOptions);
 
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
            // 打印详细错误信息
            System.err.println("转换失败:" + e.getMessage());
            e.printStackTrace(System.err);
 
            // 返回错误信息
            response.reset();
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().write("导出失败:" + e.getMessage());
            response.getWriter().flush();
        }
 
        //导出卷面封面代码
 
        ArchiveInfoVo aIV = iArchiveRecordsService.selectByRecordId(55L);
        List<ArchiveInfoVo> arsi = new ArrayList<>();
        arsi.add(aIV);
 
 
 
        String date = "";
        if(arsi.get(0).getPreparationDate()!=null) {
            System.out.println(arsi.get(0).getPreparationDate().toString() + "]]]]]]]]");
 
            System.out.println(DateUtil.parseCST(arsi.get(0).getPreparationDate().toString()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            DateTime dat = DateUtil.parseCST(arsi.get(0).getPreparationDate().toString());
            date = new SimpleDateFormat("yyyy-MM-dd").format(dat);
        }
 
 
        String tmpSec = "档号:" +
                arsi.get(0).getRecordId() +
                ";档案馆(室)号:" + arsi.get(0).getArchiveRoomNumber()+
                ";缩微号:" + arsi.get(0).getMicrofilmNumber()+
                ";发文号:" + arsi.get(0).getInquiryNumber()+
                ";案卷题名:" + arsi.get(0).getCaseTitle() +
                ";编制日期:" +  date +
                ";编制单位:" + arsi.get(0).getPreparationUnit() +
                ";保管期限:" + arsi.get(0).getRetentionPeriod() +
                ";密级:" + arsi.get(0).getSecurityClassification();
 
        String recordId = aIV.getRecordId();
        byte[] imgr = barcodeService.generateBarcodeImage(recordId);
        byte[] sedcode = pdfGenerateService.createQrCodeN(tmpSec, 100, 100);
        ExcelExp e1 = new ExcelExp("案卷封面数据",arsi, ArchiveInfoVo.class);
        ExcelExp e2 = new ExcelExp("案卷封面",  arsi, recordId, imgr,sedcode, ArchiveInfoVo.class);
        List<ExcelExp> mysheet = new ArrayList<ExcelExp>();
        mysheet.add(e1);
        mysheet.add(e2);
        ByteOutputStream bos1 = new ByteOutputStream();
        ExcelUtilManySheetSecond<List<ExcelExp>> util2 = new ExcelUtilManySheetSecond<List<ExcelExp>>(mysheet);
 
      //  util2.exportExcelManySheet(response, mysheet);
 
 
 
        //导出卷面目录代码
//        DocumentMaterials documentMaterials = new DocumentMaterials();
//        documentMaterials.setRecordId(55L);
//      //  List<DocumentMaterials> docs = documentMaterialsService.selectDocumentMaterialsList(documentMaterials);
//        List<DocumentMaterialsVo> dsvs = documentMaterialsService.findArchMInfo("55");
//      //  dsvs.get(0).setUrl("/profile/upload/2025/08/14/30_20250814212128A031.jpg");
//
//
//      //  dsvs.stream().map()
//        List<DocumentMaterialsVoSmall> list2 = dsvs.stream().map(res -> new DocumentMaterialsVoSmall(res.getNum(), res.getDocumentNumber(),res.getCreator(),
//                res.getTitle(), res.getDate(), res.getPageNumber(), res.getRemarks())).collect(Collectors.toList());
//
//        String recordId = dsvs.get(0).getRecordId();
//        byte[] imgr = barcodeService.generateBarcodeImage(recordId);
//        ExcelExp e1 = new ExcelExp("卷内目录数据",dsvs, DocumentMaterialsVo.class);
//        ExcelExp e2 = new ExcelExp("卷内数据", list2, recordId, imgr, DocumentMaterialsVoSmall.class);
//        List<ExcelExp> mysheet = new ArrayList<ExcelExp>();
//        mysheet.add(e1);
//        mysheet.add(e2);
//        ExcelUtilManySheet<List<ExcelExp>> util2 = new ExcelUtilManySheet<List<ExcelExp>>(mysheet);
       // util2.exportExcelManySheet(response, mysheet);
 
    }
 
 
 
    @PostMapping("/exportChooseArchive/{ids}")
    public void exportChooseArchive(HttpServletResponse response,  @PathVariable Long[] ids)throws Exception
    {
        //计算文件的大小
        Double siz = 0.0;
        for(int i = 0; i < ids.length; i++) {
 
            // 获取文件的保存位置,读取数据库,
            DocumentMaterials documentMaterials = new DocumentMaterials();
            documentMaterials.setRecordId(ids[i]);
            List<DocumentMaterialsVoLarge> docs = documentMaterialsService.selectDocumentMaterialsAllByRecordId(ids[i]);
            System.out.println(docs.size()+"----009");
            for (DocumentMaterialsVoLarge dc : docs) {
                if(dc!=null)
                    siz += dc.getFileSize()!=null?dc.getFileSize():0;
            }
        }
        System.out.println(siz/1000);
        //判断是否大于4G,是的话,直接抛出异常
        long maxSize = 4L * 1024 * 1024 * 1024; // 4GB in bytes
        if (siz > maxSize) {
            throw new RuntimeException("文件总大小超过4GB,无法导出");
        }
        System.out.println("092939932");
        String zipFileName ="test" +".zip";
        //生成压缩包存储地址(最后会删掉)
        String fileZip = RuoYiConfig.getProfile() + "/download/" + zipFileName;
        OutputStream os=null;
        ZipOutputStream zos = null ;
        System.out.println("==============_______________");
        System.out.println(ids.length);
        File file = new File(fileZip);
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            os = new FileOutputStream(file);
            //压缩文件
            zos = new ZipOutputStream(os);
            //拿到当前的时间
            LocalDate date = LocalDate.now();
            System.out.println("当前日期: " + date);
 
 
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            String formattedDate = date.format(formatter);
            System.out.println(formattedDate);
 
            // 生成当天导出序号
            String sequence = generateDailySequence(formattedDate);
            String fna = "GH" + formattedDate + sequence + "/";
            zos.putNextEntry(new ZipEntry(fna));
 
 
            //添加ids的全部数据到excel
            ArchiveRecords archiveRecords = new ArchiveRecords();
            archiveRecords.setIds(ids);
            List<ArchiveRecords> lis = iArchiveRecordsService.selectArchiveRecordsList(archiveRecords);
            //案卷目录导出
            ZipEntry entry = new ZipEntry(fna + "案卷目录" + ".xls");
            ExcelUtil<ArchiveRecords> util = new ExcelUtil<ArchiveRecords>(ArchiveRecords.class);
 
            zos.putNextEntry(entry);
            ByteOutputStream bos = new ByteOutputStream();
            util.byteOutputStreamExcel(bos, lis,"案卷目录", "");
            bos.writeTo(zos);
 
            //移交清单
            List<ArchiveRecordSmall> lrs = iArchiveRecordsService.findByIds(archiveRecords);
            //电子文件的个数
            System.out.println(lrs);
            System.out.println("99999999990000");
            ZipEntry entry1 = new ZipEntry(fna + "移交清单" + ".xls");
            ExcelUtil<ArchiveRecordSmall> util1 = new ExcelUtil<ArchiveRecordSmall>(ArchiveRecordSmall.class);
 
 
 
            ExcelExp e6 = new ExcelExp("移交清单","GH" + formattedDate + sequence,  lrs, ArchiveRecordSmall.class);
          //  ExcelExp e4 = new ExcelExp("案卷封面",  arsi, recordId1, imgr1,sedcode, ArchiveInfoVo.class);
            List<ExcelExp> mysheet6 = new ArrayList<ExcelExp>();
            mysheet6.add(e6);
         //   mysheet1.add(e4);
            ByteOutputStream bos6 = new ByteOutputStream();
            ExcelUtilManySheetThird<List<ExcelExp>> util6 = new ExcelUtilManySheetThird<List<ExcelExp>>(mysheet6);
 
            util6.exportExcelManySheet(bos6, mysheet6);
 
            //  System.out.println(bos2);
            zos.putNextEntry(entry1);
          //  ByteOutputStream bos1 = new ByteOutputStream();
           // util6.byteOutputStreamExcel(bos1, lrs,"移交清单", "");
            bos6.writeTo(zos);
 
 
 
 
            System.out.println(ids.length);
            System.out.println("------------------");
 
            for(int i = 0; i < ids.length; i++) {
                System.out.println(ids[i]);
                ArchiveRecords archiveRecords1 = iArchiveRecordsService.selectArchiveRecordsById(ids[i]);
                ArchiveInfoVo aIV = iArchiveRecordsService.selectByRecordId(ids[i]);
                // 获取文件的保存位置,读取数据库,
                DocumentMaterials documentMaterials = new DocumentMaterials();
                documentMaterials.setRecordId(ids[i]);
 
                //生成新的记录,不保存再数据库
                List<DocumentMaterials> docAllInfo = documentMaterialsService.SelectAllRecordsByPageNumbersToList(ids[i], archiveRecords1.getPageCount());
                //把DocumentMaterils转到docs
                List<DocumentMaterialsVoLarge> docs = new ArrayList<>();
                int nstar = 1;
 
                //统计3中材料的个数
                int texPages = 0;
                int picPages = 0;
                int patPages = 0;
                for (DocumentMaterials mater : docAllInfo) {
                    // physcialService.mySave(physcial);
                    DocumentMaterialsVoLarge docum = new DocumentMaterialsVoLarge();
                    BeanUtils.copyProperties(mater, docum);
                    docum.setRecordId(archiveRecords1.getRecordId());
                    docum.setNum(nstar++);
                    docs.add(docum);
                    if(mater.getFileStyle()!=null&&mater.getFileStyle().equals("文字材料"))
                        texPages++;
                    if(mater.getFileStyle()!=null&&mater.getFileStyle().equals("图样材料"))
                        patPages++;
                    if(mater.getFileStyle()!=null&&mater.getFileStyle().equals("照片材料"))
                        picPages++;
                }
 
 
 
                //把附件和记录一一对应
                String fileSysPath = RuoYiConfig.getUploadPath();
                AjaxResult ajax = AjaxResult.success();
                String path = fileSysPath + File.separator + ids[i];
                File desc = new File(fileSysPath + File.separator + ids[i]);
                System.out.println("44444444444444456666666666666666");
                if (!desc.exists())
                {
                    throw new RuntimeException("电子文件信息没有上传,请补充!");
                }
 
 
                Map<String, String> fileMap = new HashMap<>();
                try (Stream<Path> paths = Files.walk(Paths.get(path))) {
                    fileMap = paths
                            .filter(Files::isRegularFile)
                            .collect(Collectors.toMap(
                                    // Key: 文件名前缀(不带扩展名)
                                    Path -> {
                                        String fileNam = Path.getFileName().toString();
                                        int dotIndex = fileNam.lastIndexOf('.');
                                        return dotIndex > 0 ? fileNam.substring(0, dotIndex) : fileNam;
                                    },
                                    // Value: 文件全路径
                                    Path::toString,
                                    // 处理重复键的情况(如果有相同前缀的文件)
                                    (existing, replacement) -> existing
                            ));
 
                }
 
 
                //重新封装一下docs,和附件绑定再一起
 
                for (int k = 0; k < docs.size(); k++) {
                    DocumentMaterialsVoLarge dc = docs.get(k);
                    if (dc.getSecurityLevel() != null && (dc.getSecurityLevel().equals("该页另存") ||
                            dc.getSecurityLevel().equals("秘密") || dc.getSecurityLevel().equals("内部用途") ||
                            dc.getSecurityLevel().equals("内部用图"))) {
                        // 替换为了准备好的图像
                        String fp = fileSysPath + "\\glc.jpg";
                        Path path1 = Paths.get(fp);
                        // 拿到图像属性
                        BufferedImage bufferedImage = ImageIO.read(Files.newInputStream(path1));
                        int wid = bufferedImage.getWidth();
                        int hei = bufferedImage.getHeight();
                        double sz = Double.parseDouble(String.format("%.2f", Files.size(path1) * 1.0 / 1024));
 
                        // 拿到图像的dpi信息
                        ImageInfo info = Imaging.getImageInfo(Files.readAllBytes(path1));
                        int wdpi = info.getPhysicalWidthDpi();
                        int hdpi = info.getPhysicalHeightDpi();
 
                        // 计算fileNumber
                        //    Long fileNumber = documentMaterialsService.getFiNum(nam, recordId);
                        // 计算sizeType
                        String sizeType = getPageSize(wid * hei);
 
                        Graphics2D g2d = bufferedImage.createGraphics();
                        g2d.setFont(new java.awt.Font("宋体", Font.BOLD, 80)); // 设置字体样式和大小
                        g2d.setColor(Color.black);
                        String pageNumber = dc.getPageNumber() + "";
                        int fontHeight = g2d.getFontMetrics().getHeight();
                        int x = bufferedImage.getWidth() - g2d.getFontMetrics().stringWidth(pageNumber) - 80;
                        int y = bufferedImage.getHeight() - fontHeight / 2 - 100;
                        g2d.drawString(pageNumber, x, y);
                        g2d.dispose();
 
                        // 将BufferedImage转换为MultipartFile
                        MultipartFile multipartFile = null;
                        ByteArrayOutputStream ost = new ByteArrayOutputStream();
                        ImageIO.write(bufferedImage, "jpg", ost);
                        InputStream input = new ByteArrayInputStream(ost.toByteArray());
                        multipartFile = new MockMultipartFile(pageNumber, pageNumber + ".jpg", "text/plain", input);
 
                        // 上传并返回新文件名称
                        String fileName1 = FileUploadUtils.upload(fileSysPath, multipartFile);
                        // filePath = fileName1;
                        dc.setWidth((long) wid);
                        dc.setHeight((long) hei);
                        dc.setFileSize(sz);
                        dc.setFormat(".jpg");
                        dc.setHorizontalResolution((long) wdpi);
                        dc.setVerticalResolution((long) hdpi);
                        dc.setSizeType(sizeType);
                        fileMap.put(dc.getPageNumber()+"", fileName1);
                        //   dc.set
                        // 更新数据库
                        //   documentMaterialsService.updateByPageNumber(nam, sizeType, fileNumber, wid, hei, wdpi, hdpi, sz, fileName1, "jpg", recordId);
 
//                        urls.add(serverConfig.getUrl() + fileName1);
//                        fileNames.add(fileName1);
//                        newFileNames.add(FileUtils.getName(fileName1));
//                        originalFilenames.add(pageNumber + ".jpg");
                    }
                    else {
                        //文件名称
                        //  String pname = nams[1];
                        //   ajax.put("url", url);
                        //拿到图像属性
                        System.out.println(dc.getPageNumber());
                        String fip = fileMap.get(dc.getPageNumber().toString());
// 创建 File 对象
                        if (fip == null) {
                            // 补零到4位(根据你的需求调整位数)
                            String paddedKey = frontCompWithZore(4, dc.getPageNumber().intValue());
                            fip = fileMap.get(paddedKey);
                        }
                        File fils = new File(fip);
 
// 使用 ImageIO 读取图片
                        BufferedImage image = ImageIO.read(fils);
                        BufferedImage bufferedImage = ImageIO.read(fils);
                        int wid = bufferedImage.getWidth();
                        int hei = bufferedImage.getHeight();
                        double sz =  Double.parseDouble(String.format("%.2f", fils.length()*1.0/1024));
                        System.out.println(wid+":"+hei+":"+sz);
                        //拿到图像的dpi信息
                        byte[] bytesArray = new byte[(int) fils.length()];
 
                        FileInputStream fis = new FileInputStream(fils);
                        fis.read(bytesArray); //read file into bytes[]
 
                        ImageInfo info = Imaging.getImageInfo(bytesArray);
 
 
                        int wdpi = info.getPhysicalWidthDpi() ;
                        int hdpi = info.getPhysicalHeightDpi();
                        //      System.out.println("DPI: " + info.getPhysicalWidthDpi()+nam+"dds");
 
                        fis.close();
                        //计算fileNumber
                        //  Long fileNumber = documentMaterialsService.getFiNum(dc.getPageNumber(), id);
                        //计算sizeType
                        String sizeType = getPageSize(wid*hei);
 
                        dc.setWidth((long) wid);
                        dc.setHeight((long) hei);
                        dc.setFileSize(sz);
                        dc.setFormat(".jpg");
                        dc.setHorizontalResolution((long) wdpi);
                        dc.setVerticalResolution((long) hdpi);
                        dc.setSizeType(sizeType);
                    }
                }
 
                List<DocumentMaterialsVo> dsvs = documentMaterialsService.findArchMInfo(ids[i].toString(), archiveRecords1.getPageCount());
 
//                List<DocumentMaterialsVoLarge> docs = documentMaterialsService.selectDocumentMaterialsAllByRecordId(ids[i]);
//                System.out.println(docs.size()+"----7777");
 
 
                //.selectDocumentMaterialsList(documentMaterials);
 
                System.out.println(aIV.getInquiryNumber());
                System.out.println(aIV.getRecordId());
                String adir = aIV.getInquiryNumber() + " " + aIV.getRecordId();
                System.out.println(adir);
                System.out.println(fna+adir);
                zos.putNextEntry(new ZipEntry(fna + adir + "/"));
 
                //在里面添加文件
                boolean res = true;
                if(res) {
                    zos.putNextEntry(new ZipEntry(fna + adir + "/01-申请材料/"));
                    zos.putNextEntry(new ZipEntry(fna + adir + "/02-办案过程材料/"));
                    zos.putNextEntry(new ZipEntry(fna + adir + "/03-结论性文件/"));
                    zos.putNextEntry(new ZipEntry(fna + adir + "/04-其他材料/"));
                    zos.putNextEntry(new ZipEntry(fna + adir + "/05-档案变更材料/"));
                    zos.putNextEntry(new ZipEntry(fna + adir + "/06-业务数据/"));
                    res = false;
                }
                //添加07  的pdf
                //pdf目录封面
//                String pdfPathF = "07-案卷封面.pdf";
//                pdfGenerateService.generatePdf(pdfPathF, ids[i]);
//                // 2. 压缩PDF到ZIP文件
//                // 添加PDF文件到ZIP
//                ZipEntry zipEntry2 = new ZipEntry(fna + adir +"/"+pdfPathF);
//                zos.putNextEntry(zipEntry2);
//
//                // 读取PDF文件内容并写入ZIP
//                try (FileInputStream fis = new FileInputStream(pdfPathF)) {
//                    byte[] buffer = new byte[1024];
//                    int len;
//                    while ((len = fis.read(buffer)) > 0) {
//                        zos.write(buffer, 0, len);
//                    }
//                }
 
 
 
 
 
                //09-备考表.pdf
 
 
 
 
//                pdfGenerateService.generateFileStyleInfo(pdf09Path, aIV.getRecordId(), ids[i]);
//                // 2. 压缩PDF到ZIP文件
//                // 添加PDF文件到ZIP
//                ZipEntry zipEntry4 = new ZipEntry(fna + adir +"/"+pdf09Path);
//                zos.putNextEntry(zipEntry4);
//
//                // 读取PDF文件内容并写入ZIP
//                try (FileInputStream fis = new FileInputStream(pdf09Path)) {
//                    byte[] buffer = new byte[1024];
//                    int len;
//                    while ((len = fis.read(buffer)) > 0) {
//                        zos.write(buffer, 0, len);
//                    }
//                }
 
 
                //09-备考表.pdf
                String pdf09Path = "09-备考表.pdf";
                //  pdfGenerateService.generateFileStyleInfo(pdf09Path, aIV.getRecordId(), id);
                //拿到相关数据
                List<DocumentMaterialFileStyle> dmfs = documentMaterialsService.findFileStyleInfo(Math.toIntExact(ids[i]));
 
                LocalDate currentDate = LocalDate.now();
 
 
                String cdt = currentDate.getYear()+"年"+currentDate.getMonthValue()+"月"+currentDate.getDayOfMonth()+"日";
 
                HashMap<String, Object> hs = new HashMap<String, Object>();
                int allPages = 0;
//                int texPages = 0;
//                int picPages = 0;
//                int patPages = 0;
//                if(!dmfs.isEmpty())
//                {
//                    for(DocumentMaterialFileStyle documentMaterialFileStyle:dmfs)
//                    {
//                        if(documentMaterialFileStyle.getFileStyle()!=null&&documentMaterialFileStyle.getFileStyle().equals("文字材料"))
//                            texPages = documentMaterialFileStyle.getCnt();
//                        if(documentMaterialFileStyle.getFileStyle()!=null&&documentMaterialFileStyle.getFileStyle().equals("图样材料"))
//                            patPages = documentMaterialFileStyle.getCnt();
//                        if(documentMaterialFileStyle.getFileStyle()!=null&&documentMaterialFileStyle.getFileStyle().equals("照片材料"))
//                            picPages = documentMaterialFileStyle.getCnt();
//                    }
//                }
 
 
                String compName = "广州盈家档案管理有限公司";
                String li_person = "仇翀";
                String sh_person = "曾瑞莹";
 
                if(!StringUtils.isEmpty(archiveRecords1.getLiPerson()))
                    li_person = archiveRecords1.getLiPerson();
                ArchiveProjectName tmp = new ArchiveProjectName();
                tmp.setName(archiveRecords1.getProjectName());
                List<ArchiveProjectName> projectName = iArchiveProjectNameService.selectArchiveProjectNameList(tmp);
                if(!projectName.isEmpty())
                {
                    if(!StringUtils.isEmpty(projectName.get(0).getCompanyName()))
                        compName = projectName.get(0).getCompanyName();
                    if(!StringUtils.isEmpty(projectName.get(0).getCreatePerson()))
                        sh_person = projectName.get(0).getCreatePerson();
                }
                allPages = texPages + picPages + patPages;
                hs.put("pages", allPages);
                hs.put("patPages", patPages);
                hs.put("picPages", picPages);
                hs.put("texPages", texPages);
                hs.put("volumeNumber", aIV.getRecordId());
                hs.put("company", compName);
                hs.put("liPerson", li_person);
                hs.put("shPerson", sh_person);
                hs.put("time", cdt);
 
                if (!getLicense()) {
                    System.out.println("没有相关证书!");
                }
 
 
                try {
 
                    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
                    org.springframework.core.io.Resource resource = resolver.getResource("classpath:09.docx");
//                String filepath = resource.getFile().getAbsolutePath();
//                // 通过 XWPFTemplate 编译文件并渲染数据到模板中
//                XWPFTemplate template = XWPFTemplate.compile(filepath).render(hs
//                       );
 
                    InputStream inputStream = resource.getInputStream();
                    // 通过 XWPFTemplate 编译文件并渲染数据到模板中
                    XWPFTemplate template = XWPFTemplate.compile(inputStream).render(hs
                    );
 
                    String renderedDocPath = "rendered_output.docx";
                    File renderedFile = new File(renderedDocPath);
                    try {
                        // 将完成数据渲染的文档写出
                        template.writeAndClose(new FileOutputStream(renderedFile));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
 
                    com.aspose.words.Document doc = new com.aspose.words.Document("rendered_output.docx");
                    // 创建临时字节输出流
                    ByteArrayOutputStream baobk = new ByteArrayOutputStream();
                    // 将Word文档转换为PDF字节数组
                    doc.save(baobk, com.aspose.words.SaveFormat.PDF);//ȫ��֧��DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF �໥ת��
                   ZipEntry zipEntry4 = new ZipEntry(fna + adir +"/"+pdf09Path);
                zos.putNextEntry(zipEntry4);
                    baobk.writeTo(zos);
 
                } catch (Exception e) {
                    e.printStackTrace();
                }
 
 
 
             //   com.aspose.words.Document doc = new com.aspose.words.Document("09-备考表.docx");
 
 
 
 
 
 
 
 
                //excel 卷内封面导出zip
                ZipEntry entryiv = new ZipEntry(fna + adir +"/"+"案卷封面" + ".xls");
 
                List<ArchiveInfoVo> arsi = new ArrayList<>();
                arsi.add(aIV);
 
                String dates = "";
                if(arsi.get(0).getPreparationDate()!=null) {
                    System.out.println(arsi.get(0).getPreparationDate().toString() + "]]]]]]]]");
 
                    System.out.println(DateUtil.parseCST(arsi.get(0).getPreparationDate().toString()));
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    DateTime dat = DateUtil.parseCST(arsi.get(0).getPreparationDate().toString());
                    dates = new SimpleDateFormat("yyyy-MM-dd").format(dat);
                }
 
 
                String tmpSec = "档号:" +
                        arsi.get(0).getRecordId() +
                        ";档案馆(室)号:" + arsi.get(0).getArchiveRoomNumber()+
                        ";缩微号:" + arsi.get(0).getMicrofilmNumber()+
                        ";发文号:" + arsi.get(0).getInquiryNumber()+
                        ";案卷题名:" + arsi.get(0).getCaseTitle() +
                        ";编制日期:" +  dates +
                        ";编制单位:" + arsi.get(0).getPreparationUnit() +
                        ";保管期限:" + arsi.get(0).getRetentionPeriod() +
                        ";密级:" + arsi.get(0).getSecurityClassification();
 
 
 
                String recordId1 = aIV.getRecordId();
                byte[] imgr1 = barcodeService.generateBarcodeImage(recordId1);
                byte[] sedcode = pdfGenerateService.createQrCodeN(tmpSec, 200, 200);
                ExcelExp e3 = new ExcelExp("案卷封面数据",arsi, ArchiveInfoVo.class);
                ExcelExp e4 = new ExcelExp("案卷封面",  arsi, recordId1, imgr1,sedcode, ArchiveInfoVo.class);
                List<ExcelExp> mysheet1 = new ArrayList<ExcelExp>();
                mysheet1.add(e3);
                mysheet1.add(e4);
                ByteOutputStream bos2 = new ByteOutputStream();
                ExcelUtilManySheetSecond<List<ExcelExp>> util3 = new ExcelUtilManySheetSecond<List<ExcelExp>>(mysheet1);
 
                util3.exportExcelManySheet(bos2, mysheet1);
 
                //  System.out.println(bos2);
                zos.putNextEntry(entryiv);
 
 
                bos2.writeTo(zos);
 
 
                //pdf目录封面
                String pdfPathF = "07-案卷封面.pdf";
                // pdfGenerateService.generatePdf(pdfPathF, id);
 
                try {
                    if (!getLicenseExcel()) {
                        System.out.println("授权失败");
                        // return ;
                    }
                    // 读取Excel文件
                    com.aspose.cells.Workbook wb = poiToAspose(util3.getWb());
 
                    // 获取需要导出的sheet(索引从0开始)
                    int targetSheetIndex = 1;
                    com.aspose.cells.Worksheet targetSheet = wb.getWorksheets().get(targetSheetIndex);
                    targetSheet.autoFitRows(true);
                    System.out.println("当前sheet名称:" + targetSheet.getName());
                    System.out.println("当前sheet索引:" + targetSheet.getIndex());
 
                    // 隐藏所有其他工作表
                    for (int j = 0; j < wb.getWorksheets().getCount(); j++) {
                        if (j != targetSheetIndex) {
                            wb.getWorksheets().get(j).setVisible(false);
                        }
                    }
 
                    // 设置活动工作表为目标工作表
                    wb.getWorksheets().setActiveSheetIndex(targetSheetIndex);
                    // 创建PDF保存选项
                    com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
                    pdfSaveOptions.setCompliance(com.aspose.cells.PdfCompliance.PDF_A_1_B);
                    // 确保字体嵌入到PDF中
 
 
                    // 创建临时字节输出流
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
                    // 将新的Workbook保存为PDF到临时流
                    //   newWorkbook.save(baos, com.aspose.cells.SaveFormat.PDF);
                    wb.save(baos, pdfSaveOptions);
 
                    // 将PDF添加到ZIP文件
                    ZipEntry entry07 = new ZipEntry(fna + adir +"/"+pdfPathF);
                    zos.putNextEntry(entry07);
                    zos.write(baos.toByteArray());
                    //  zos.closeEntry();
                    // 直接将原始工作簿保存为PDF(只包含可见的工作表)
 
                    long now = System.currentTimeMillis();
                    //   System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
                } catch (Exception e) {
                    e.printStackTrace();
                    // 打印详细错误信息
                    System.err.println("转换失败:" + e.getMessage());
                    e.printStackTrace(System.err);
                }
 
//            ExcelUtil<ArchiveInfoVo> utilsv = new ExcelUtil<ArchiveInfoVo>(ArchiveInfoVo.class);
//
//
//            ByteOutputStream boss = new ByteOutputStream();
//            List<ArchiveInfoVo> aivs = new ArrayList<>();
//            aivs.add(aIV);
//            utilsv.byteOutputStreamExcel(boss, aivs,"Date List", "");
 
 
 
 
                //写入电子目录  xsxl
 
                ZipEntry entry5 = new ZipEntry(fna + adir +"/"+"电子文件目录" + ".xls");
                ExcelUtil<DocumentMaterialsVoLarge> util5 = new ExcelUtil<DocumentMaterialsVoLarge>(DocumentMaterialsVoLarge.class);
 
                zos.putNextEntry(entry5);
                ByteOutputStream bos5 = new ByteOutputStream();
                util5.byteOutputStreamExcel(bos5, docs,"电子文件目录", "");
                bos5.writeTo(zos);
 
                //拿到卷内目录的excel
                List<DocumentMaterialsVoSmall> list2 = dsvs.stream().map(res1 -> new DocumentMaterialsVoSmall(res1.getNum(), res1.getDocumentNumber(),res1.getCreator(),
                        res1.getTitle(), res1.getDate(), res1.getPageNumberFormatted(), res1.getRemarks())).collect(Collectors.toList());
                if(!dsvs.isEmpty()) {
                    String recordId = dsvs.get(0).getRecordId();
                    byte[] imgr = barcodeService.generateBarcodeImage(recordId);
                    ExcelExp e1 = new ExcelExp("卷内目录数据", dsvs, DocumentMaterialsVo.class);
                    ExcelExp e2 = new ExcelExp("卷内数据", list2, recordId, imgr, DocumentMaterialsVoSmall.class);
                    List<ExcelExp> mysheet = new ArrayList<ExcelExp>();
                    mysheet.add(e1);
                    mysheet.add(e2);
                    ExcelUtilManySheet<List<ExcelExp>> util2 = new ExcelUtilManySheet<List<ExcelExp>>(mysheet);
                    ZipEntry entr = new ZipEntry(fna + adir + "/" + "卷内目录" + ".xls");
                    // ExcelUtil<DocumentMaterialsVo> util1 = new ExcelUtil<DocumentMaterialsVo>(DocumentMaterialsVo.class);
                    System.out.println(dsvs);
                    zos.putNextEntry(entr);
                    ByteOutputStream bos8 = new ByteOutputStream();
 
                    util2.exportExcelManySheet(bos8, mysheet);
 
                    //   util1.byteOutputStreamExcel(bos1, dsvs,"Date List", "");
                    bos8.writeTo(zos);
 
 
 
 
                    //08-卷内卷内目录的pdf
                    String pdf08Path= "08-卷内目录.pdf";
                    try {
                        if (!getLicenseExcel()) {
                            System.out.println("授权失败");
                            // return ;
                        }
                        // 读取Excel文件
                        com.aspose.cells.Workbook wb1 = poiToAspose(util2.getWb());
 
                        // 获取需要导出的sheet(索引从0开始)
                        int targetSheetIndex = 1;
                        com.aspose.cells.Worksheet targetSheet = wb1.getWorksheets().get(targetSheetIndex);
                        targetSheet.autoFitRows(true);
                        System.out.println("当前sheet名称:" + targetSheet.getName());
                        System.out.println("当前sheet索引:" + targetSheet.getIndex());
 
                        // 隐藏所有其他工作表
                        for (int j = 0; j < wb1.getWorksheets().getCount(); j++) {
                            if (j != targetSheetIndex) {
                                wb1.getWorksheets().get(j).setVisible(false);
                            }
                        }
 
                        // 设置活动工作表为目标工作表
                        wb1.getWorksheets().setActiveSheetIndex(targetSheetIndex);
                        // 创建PDF保存选项
                        com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
                        pdfSaveOptions.setCompliance(com.aspose.cells.PdfCompliance.PDF_A_1_B);
                        // 创建临时字节输出流
                        ByteArrayOutputStream baosm = new ByteArrayOutputStream();
 
                        // 将新的Workbook保存为PDF到临时流
                        //   newWorkbook.save(baos, com.aspose.cells.SaveFormat.PDF);
                        wb1.save(baosm, pdfSaveOptions);
 
                        // 将PDF添加到ZIP文件
                        ZipEntry entry2 = new ZipEntry(fna + adir +"/"+pdf08Path);
                        zos.putNextEntry(entry2);
                        zos.write(baosm.toByteArray());
                        //  zos.closeEntry();
                        // 直接将原始工作簿保存为PDF(只包含可见的工作表)
 
                        long now = System.currentTimeMillis();
                        //   System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 打印详细错误信息
                        System.err.println("转换失败:" + e.getMessage());
                        e.printStackTrace(System.err);
                    }
 
 
                }
                //把excel转为pdf
 
//
//                //08-卷内卷内目录的pdf
//                String pdf08Path= "08-卷内目录.pdf";
//                List<DocumentMaterialsVo> list3 = dsvs;
//                if(list3.size()>0) {
//                    pdfGenerateService.generateFileDirectoryPdf(pdf08Path, list3);
//                    ZipEntry zipEntry3 = new ZipEntry(fna + adir +"/"+pdf08Path);
//                    zos.putNextEntry(zipEntry3);
//
//                    // 读取PDF文件内容并写入ZIP
//                    try (FileInputStream fis = new FileInputStream(pdf08Path)) {
//                        byte[] buffer = new byte[1024];
//                        int len;
//                        while ((len = fis.read(buffer)) > 0) {
//                            zos.write(buffer, 0, len);
//                        }
//                    }
//                }
//
//
 
 
 
                byte[] buf = new byte[1024];
                for (DocumentMaterialsVoLarge dc : docs) {
                    String filePath = fileMap.get(dc.getPageNumber().toString());
 
                //    filePath = filePath.replace("/profile/", RuoYiConfig.getProfile() + "/");
 
                    System.out.println(filePath);
                    if (filePath == null) {
                        // 补零到4位(根据你的需求调整位数)
                        String paddedKey = frontCompWithZore(4, dc.getPageNumber().intValue());
                        filePath = fileMap.get(paddedKey);
                    }
                    if(filePath==null)
                        continue;
 
                    if(filePath.contains("profile"))
                        filePath = filePath.replace("/profile/", RuoYiConfig.getProfile() + "/");
 
                    File tempFile = new File(filePath);
 
                    //在压缩包中添加文件夹
 
                    //得到文件名frontCompWithZore(4, dc.get)+
 
                    String fname = "";
                    if(dc.getFileNumber()!=null&&dc.getPageNumber()!=null) {
                        fname = frontCompWithZore(4, dc.getFileNumber().intValue()) + "-" + dc.getTitle() + "-" + frontCompWithZore(4, dc.getPageNumber().intValue()) + "."
                                + filePath.split("\\.")[1];
                        if (dc.getStage().equals("01-申请材料"))
                            zos.putNextEntry(new ZipEntry(fna + adir + "/01-申请材料/" + fname));
                        else if (dc.getStage().equals("02-办案过程材料"))
                            zos.putNextEntry(new ZipEntry(fna + adir + "/02-办案过程材料/" + fname));
                        else if (dc.getStage().equals("03-结论性文件"))
                            zos.putNextEntry(new ZipEntry(fna + adir + "/03-结论性文件/" + fname));
                        else if (dc.getStage().equals("04-其他材料")) {
                            zos.putNextEntry(new ZipEntry(fna + adir + "/04-其他材料/" + fname));
                        } else if (dc.getStage().equals("05-档案变更材料"))
                            zos.putNextEntry(new ZipEntry(fna + adir + "/05-档案变更材料/" + fname));
                        else if (dc.getStage().equals("06-业务数据"))
                            zos.putNextEntry(new ZipEntry(fna + adir + "/06-业务数据/" + fname));
                        else
                            zos.putNextEntry(new ZipEntry(fna + adir + "/" + fname));
 
                }
 
                int len;
                FileInputStream in = new FileInputStream(tempFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                  //  zos.putNextEntry(new ZipEntry("04-其他材料"));
                zos.closeEntry();
                in.close();
            }
        }
 
        //删除压缩包
//            if(file.exists()){
//                file.delete();
//            }
 
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            //关闭流
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭流
            if(os!= null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
 
        System.out.println(file.getName());
        System.out.println(file.getTotalSpace());
        //    file.
        writeFileToRes(response, file.getName(), file);
 
    }
 
 
 
 
    /**
     * 打包下载
     * @param response
     * @param
     */
    @PostMapping("/export/{id}")
 
    public void packDownload(HttpServletResponse response,  @PathVariable Long id) throws Exception {
 
 
        // 获取文件的保存位置,读取数据库,
        DocumentMaterials documentMaterials = new DocumentMaterials();
        documentMaterials.setRecordId(id);
        //   List<DocumentMaterialsVoLarge> docs = documentMaterialsService.selectDocumentMaterialsAllByRecordId(id);
        //根据id拿到pageNumber
        ArchiveInfoVo aIV = iArchiveRecordsService.selectByRecordId(id);
        System.out.println(aIV.getPageCount() + "++++++++++++++++==");
        //生成新的记录,不保存再数据库
        List<DocumentMaterials> docAllInfo = documentMaterialsService.SelectAllRecordsByPageNumbersToList(id, aIV.getPageCount());
        if (docAllInfo==null||docAllInfo.isEmpty())
        {
            throw new RuntimeException("请补充完整信息,然后导出ISO包!");
        }
        //把DocumentMaterils转到docs
        List<DocumentMaterialsVoLarge> docs = new ArrayList<>();
        int nstar = 1;
        int texPages = 0;
        int patPages = 0;
        int picPages = 0;
        for (DocumentMaterials mater : docAllInfo) {
            // physcialService.mySave(physcial);
            DocumentMaterialsVoLarge docum = new DocumentMaterialsVoLarge();
            BeanUtils.copyProperties(mater, docum);
            docum.setRecordId(aIV.getRecordId());
            docum.setNum(nstar++);
            docs.add(docum);
            if(mater.getFileStyle()!=null&&mater.getFileStyle().equals("文字材料"))
                texPages++;
            if(mater.getFileStyle()!=null&&mater.getFileStyle().equals("图样材料"))
                patPages++;
            if(mater.getFileStyle()!=null&&mater.getFileStyle().equals("照片材料"))
                picPages++;
        }
        System.out.println(docs.size()+"----009");
 
 
                //.selectDocumentMaterialsList(documentMaterials);
 
        //把附件和记录一一对应
        String fileSysPath = RuoYiConfig.getUploadPath();
        AjaxResult ajax = AjaxResult.success();
        String path = fileSysPath + File.separator + id;
        File desc = new File(fileSysPath + File.separator + id);
        System.out.println("44444444444444456666666666666666");
        if (!desc.exists())
        {
            throw new RuntimeException("电子文件信息没有上传,请补充!");
        }
 
 
        Map<String, String> fileMap = new HashMap<>();
        try (Stream<Path> paths = Files.walk(Paths.get(path))) {
            fileMap = paths
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toMap(
                            // Key: 文件名前缀(不带扩展名)
                            Path -> {
                                String fileNam = Path.getFileName().toString();
                                int dotIndex = fileNam.lastIndexOf('.');
                                return dotIndex > 0 ? fileNam.substring(0, dotIndex) : fileNam;
                            },
                            // Value: 文件全路径
                            Path::toString,
                            // 处理重复键的情况(如果有相同前缀的文件)
                            (existing, replacement) -> existing
                    ));
 
        }
        List<DocumentMaterialsVo> dsvs = documentMaterialsService.findArchMInfo(id.toString(), aIV.getPageCount());
 
        //重新封装一下docs,和附件绑定再一起
 
        for (int i = 0; i < docs.size(); i++) {
            DocumentMaterialsVoLarge dc = docs.get(i);
            if (dc.getSecurityLevel() != null && (dc.getSecurityLevel().equals("该页另存") ||
                    dc.getSecurityLevel().equals("秘密") || dc.getSecurityLevel().equals("内部用途") ||
                    dc.getSecurityLevel().equals("内部用图"))) {
                // 替换为了准备好的图像
                String fp = fileSysPath + "\\glc.jpg";
                Path path1 = Paths.get(fp);
                // 拿到图像属性
                BufferedImage bufferedImage = ImageIO.read(Files.newInputStream(path1));
                int wid = bufferedImage.getWidth();
                int hei = bufferedImage.getHeight();
                double sz = Double.parseDouble(String.format("%.2f", Files.size(path1) * 1.0 / 1024));
 
                // 拿到图像的dpi信息
                ImageInfo info = Imaging.getImageInfo(Files.readAllBytes(path1));
                int wdpi = info.getPhysicalWidthDpi();
                int hdpi = info.getPhysicalHeightDpi();
 
                // 计算fileNumber
                //    Long fileNumber = documentMaterialsService.getFiNum(nam, recordId);
                // 计算sizeType
                String sizeType = getPageSize(wid * hei);
 
                Graphics2D g2d = bufferedImage.createGraphics();
                g2d.setFont(new java.awt.Font("宋体", Font.BOLD, 80)); // 设置字体样式和大小
                g2d.setColor(Color.black);
                String pageNumber = dc.getPageNumber() + "";
                int fontHeight = g2d.getFontMetrics().getHeight();
                int x = bufferedImage.getWidth() - g2d.getFontMetrics().stringWidth(pageNumber) - 80;
                int y = bufferedImage.getHeight() - fontHeight / 2 - 100;
                g2d.drawString(pageNumber, x, y);
                g2d.dispose();
 
                // 将BufferedImage转换为MultipartFile
                MultipartFile multipartFile = null;
                ByteArrayOutputStream ost = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, "jpg", ost);
                InputStream input = new ByteArrayInputStream(ost.toByteArray());
                multipartFile = new MockMultipartFile(pageNumber, pageNumber + ".jpg", "text/plain", input);
 
                // 上传并返回新文件名称
                String fileName1 = FileUploadUtils.upload(fileSysPath, multipartFile);
               // filePath = fileName1;
                dc.setWidth((long) wid);
                dc.setHeight((long) hei);
                dc.setFileSize(sz);
                dc.setFormat(".jpg");
                dc.setHorizontalResolution((long) wdpi);
                dc.setVerticalResolution((long) hdpi);
                dc.setSizeType(sizeType);
                System.out.println(fileName1);
                System.out.println("gggggggggggggggg999999999999");
                fileMap.put(dc.getPageNumber()+"", fileName1);
             //   dc.set
                // 更新数据库
                //   documentMaterialsService.updateByPageNumber(nam, sizeType, fileNumber, wid, hei, wdpi, hdpi, sz, fileName1, "jpg", recordId);
 
//                        urls.add(serverConfig.getUrl() + fileName1);
//                        fileNames.add(fileName1);
//                        newFileNames.add(FileUtils.getName(fileName1));
//                        originalFilenames.add(pageNumber + ".jpg");
            }
            else {
                //文件名称
              //  String pname = nams[1];
             //   ajax.put("url", url);
                //拿到图像属性
                System.out.println(dc.getPageNumber());
                String fip = fileMap.get(dc.getPageNumber().toString());
                // 如果直接匹配失败,尝试补零匹配
                if (fip == null) {
                    // 补零到4位(根据你的需求调整位数)
                    String paddedKey = frontCompWithZore(4, dc.getPageNumber().intValue());
                    fip = fileMap.get(paddedKey);
                }
// 创建 File 对象
                if(fip==null||fip.equals(""))
                {
                    throw new RuntimeException("电子文件信息没有上传完整,请补充!");
 
 
                }
 
                File file = new File(fip);
 
// 使用 ImageIO 读取图片
                BufferedImage image = ImageIO.read(file);
                BufferedImage bufferedImage = ImageIO.read(file);
                int wid = bufferedImage.getWidth();
                int hei = bufferedImage.getHeight();
                double sz =  Double.parseDouble(String.format("%.2f", file.length()*1.0/1024));
                System.out.println(wid+":"+hei+":"+sz);
                //拿到图像的dpi信息
                byte[] bytesArray = new byte[(int) file.length()];
 
                FileInputStream fis = new FileInputStream(file);
                fis.read(bytesArray); //read file into bytes[]
 
                ImageInfo info = Imaging.getImageInfo(bytesArray);
 
 
                int wdpi = info.getPhysicalWidthDpi() ;
                int hdpi = info.getPhysicalHeightDpi();
          //      System.out.println("DPI: " + info.getPhysicalWidthDpi()+nam+"dds");
 
                fis.close();
                //计算fileNumber
              //  Long fileNumber = documentMaterialsService.getFiNum(dc.getPageNumber(), id);
                //计算sizeType
                String sizeType = getPageSize(wid*hei);
 
                dc.setWidth((long) wid);
                dc.setHeight((long) hei);
                dc.setFileSize(sz);
                dc.setFormat(".jpg");
                dc.setHorizontalResolution((long) wdpi);
                dc.setVerticalResolution((long) hdpi);
                dc.setSizeType(sizeType);
            }
        }
        System.out.println(dsvs.size());
        List<String> paths = new ArrayList<>();
//        System.out.println(docs);
        if (docs.size() == 1) {  // 直接下载
            String filePath = paths.get(0);
            filePath = filePath.replace("/profile/", RuoYiConfig.getProfile() + "/");
 
            File file = new File(filePath);
            if (!file.exists()) {
                throw new Exception("文件不存在");
            }
            String suffix = filePath.substring(filePath.lastIndexOf("."));
            // 输出文件流
            writeFileToRes(response, "user" + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + suffix, file);
        } else {  // 压缩之后在进行下载
            //压缩包名称(会拼上当前时间)
            System.out.println(90);
            String datumName = "user";
            //压缩文件
            List<String> filePathList = paths;
            //把docmentMaterial转为
            File file = compressedFileToZip(docs, dsvs, aIV, id, fileMap, texPages, patPages, picPages);
            System.out.println(file.getName());
 
            String fileName =aIV.getRecordId()+".zip";
 
            //输出文件流
            writeFileToRes(response, file.getName(), file);
            //删除压缩包
            if(file.exists()){
                file.delete();
            }
        }
    }
    // 输出文件流到response
    private void writeFileToRes(HttpServletResponse response, String fileName, File file) throws IOException {
 
 
        String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
        String filePath = RuoYiConfig.getDownloadPath() + fileName;
        if(file.exists())
            System.out.println("322329323232323");
        System.out.println(filePath+"0009999999999");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, realFileName);
     //   response.addHeader("Content-Disposition", "attachment;filename=fileName" + ".xls");
 
        FileUtils.writeBytes(filePath, response.getOutputStream());
 
    }
    public String frontCompWithZore(int formatLength,int formatNumber){
        /**
         * 0 指前面补充零
         * formatLength 字符总长度为 formatLength
         * inputNumber 格式化数字
         * d 代表为正数。
         */
        String newString = String.format("%0"+formatLength+"d", formatNumber);
        return newString;
    }
 
 
    public  com.aspose.cells.Workbook poiToAspose(org.apache.poi.ss.usermodel.Workbook poiWorkbook) throws Exception {
        // 临时文件路径
        String tempFilePath = "temp_workbook.xlsx";
 
        try {
            // 1. 将Apache POI Workbook保存为临时文件
            try (FileOutputStream fos = new FileOutputStream(tempFilePath)) {
                poiWorkbook.write(fos);
            }
 
            // 2. 使用Aspose加载临时文件
            com.aspose.cells.Workbook asposeWorkbook = new com.aspose.cells.Workbook(tempFilePath);
 
            return asposeWorkbook;
 
        } finally {
            // 清理临时文件
            File tempFile = new File(tempFilePath);
            if (tempFile.exists()) {
                tempFile.delete();
            }
        }
    }
 
 
 
 
    private  PdfPCell ImageSet(int high) throws Exception {
      //  byte[] fileByte = toByteArray("D:\\project\\archive\\download\\12.jpg");
//
//
//        FileInputStream fis = new FileInputStream("D:\\project\\archive\\download\\56.png");
//        byte[] imageBytes = new byte[fis.available()];
//        fis.read(imageBytes);
//        fis.close();
//        Jpeg jpeg = new Jpeg(imageBytes);
//        jpeg.scaleAbsolute(70, 50);
        byte[] imageBytes = barcodeService.generateBarcodeImage("D3.4.1-05-2024-0002");
// 加载PNG图片
        Image img = Image.getInstance(imageBytes);
        // 设置图片在PDF中的位置(可选)
        img.setAbsolutePosition(100, 700);
        // 将图片添加到PDF文档中
        PdfPCell pdfPCell = new PdfPCell(img);
        pdfPCell.setMinimumHeight(high);
        pdfPCell.setUseAscender(true); // 设置可以居中
        pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
        pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
        return pdfPCell;
    }
 
 
    // 压缩文件
    private File compressedFileToZip(List<DocumentMaterialsVoLarge> docs, List<DocumentMaterialsVo> dsvs,   ArchiveInfoVo aIV, Long id,   Map<String, String> fileMap,
     int texPages,
    int patPages,
    int picPages) throws Exception {
        //压缩包具体名称(拼接时间戳防止重名)
        String datumName = "";
        String zipFileName =dsvs.get(0).getDocumentNumber()+aIV.getRecordId()+ ".zip";
        //生成压缩包存储地址(最后会删掉)
        String fileZip = RuoYiConfig.getProfile() + "/download/" + zipFileName;
        OutputStream os=null;
        ZipOutputStream zos = null ;
        System.out.println("==============_______________");
        File file = new File(fileZip);
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            os=new FileOutputStream(file);
            //压缩文件
            zos = new ZipOutputStream(os);
 
 
 
                //09-备考表.pdf
            String pdf09Path = "09-备考表.pdf";
          //  pdfGenerateService.generateFileStyleInfo(pdf09Path, aIV.getRecordId(), id);
            //拿到相关数据
          //  List<DocumentMaterialFileStyle> dmfs = documentMaterialsService.findFileStyleInfo(Math.toIntExact(id));
 
            LocalDate currentDate = LocalDate.now();
 
 
            String cdt = currentDate.getYear()+"年"+currentDate.getMonthValue()+"月"+currentDate.getDayOfMonth()+"日";
 
            HashMap<String, Object> hs = new HashMap<String, Object>();
            int allPages = 0;
//            int texPages = 0;
//            int picPages = 0;
//            int patPages = 0;
//            if(!docs.isEmpty())
//            {
//                for(DocumentMaterialsVoLarge documentMaterialFileStyle:docs)
//                {
//                    if(documentMaterialFileStyle!=null&&documentMaterialFileStyle.getFileStyle().equals("文字材料"))
//                        texPages = documentMaterialFileStyle.getCnt();
//                    if(documentMaterialFileStyle.getFileStyle()!=null&&documentMaterialFileStyle.getFileStyle().equals("图样材料"))
//                        patPages = documentMaterialFileStyle.getCnt();
//                    if(documentMaterialFileStyle.getFileStyle()!=null&&documentMaterialFileStyle.getFileStyle().equals("照片材料"))
//                        picPages = documentMaterialFileStyle.getCnt();
//                }
//            }
 
            String compName = "广州盈家档案管理有限公司";
            String li_person = "仇翀";
            String sh_person = "曾瑞莹";
            ArchiveRecords archiveRecords = iArchiveRecordsService.selectArchiveRecordsById(id);
            if(!StringUtils.isEmpty(archiveRecords.getLiPerson()))
                li_person = archiveRecords.getLiPerson();
            ArchiveProjectName tmp = new ArchiveProjectName();
            tmp.setName(archiveRecords.getProjectName());
            List<ArchiveProjectName> projectName = iArchiveProjectNameService.selectArchiveProjectNameList(tmp);
            if(!projectName.isEmpty())
            {
                if(!StringUtils.isEmpty(projectName.get(0).getCompanyName()))
                    compName = projectName.get(0).getCompanyName();
                if(!StringUtils.isEmpty(projectName.get(0).getCreatePerson()))
                    sh_person = projectName.get(0).getCreatePerson();
            }
 
            allPages = texPages + picPages + patPages;
            hs.put("pages", allPages);
            hs.put("patPages", patPages);
            hs.put("picPages", picPages);
            hs.put("texPages", texPages);
            hs.put("volumeNumber", aIV.getRecordId());
            hs.put("company", compName);
            hs.put("liPerson", li_person);
            hs.put("shPerson", sh_person);
            hs.put("time", cdt);
 
            if (!getLicense()) {
                System.out.println("没有相关证书!");
            }
 
 
            try {
 
                // 获取 Word 模板所在路径
                ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
                org.springframework.core.io.Resource resource = resolver.getResource("classpath:09.docx");
//                String filepath = resource.getFile().getAbsolutePath();
//                // 通过 XWPFTemplate 编译文件并渲染数据到模板中
//                XWPFTemplate template = XWPFTemplate.compile(filepath).render(hs
//                       );
 
                InputStream inputStream = resource.getInputStream();
                    // 通过 XWPFTemplate 编译文件并渲染数据到模板中
                    XWPFTemplate template = XWPFTemplate.compile(inputStream).render(hs
                    );
 
 
 
 
 
 
                String renderedDocPath = "rendered_output.docx";
                File renderedFile = new File(renderedDocPath);
                try {
                    // 将完成数据渲染的文档写出
                    template.writeAndClose(new FileOutputStream(renderedFile));
                } catch (IOException e) {
                    e.printStackTrace();
                }
 
                com.aspose.words.Document doc = new com.aspose.words.Document("rendered_output.docx");
                // 创建临时字节输出流
                ByteArrayOutputStream baobk = new ByteArrayOutputStream();
 
                // 将Word文档转换为PDF字节数组
                doc.save(baobk, com.aspose.words.SaveFormat.PDF);//ȫ��֧��DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF �໥ת��
//                byte[] pdfBytes = baobk.toByteArray();
 
                // 获取PDF总页数
 
 
                // 将PDF添加到ZIP文件
                ZipEntry entry09 = new ZipEntry(pdf09Path);
                zos.putNextEntry(entry09);
                baobk.writeTo(zos);
            } catch (Exception e) {
                e.printStackTrace();
            }
 
 
 
           // com.aspose.words.Document doc = new com.aspose.words.Document("09.docx");
 
 
 
 
 
//            // 压缩PDF到ZIP文件
//            // 添加PDF文件到ZIP
//            ZipEntry zipEntry1 = new ZipEntry(pdf09Path);
//            zos.putNextEntry(zipEntry1);
//
//            // 读取PDF文件内容并写入ZIP
//            try (FileInputStream fis = new FileInputStream(pdf09Path)) {
//                byte[] buffer = new byte[1024];
//                int len;
//                while ((len = fis.read(buffer)) > 0) {
//                    zos.write(buffer, 0, len);
//                }
//            }
 
 
 
 
                //excel 卷内封面导出zip
            ZipEntry entryiv = new ZipEntry("案卷封面" + ".xls");
 
            List<ArchiveInfoVo> arsi = new ArrayList<>();
            arsi.add(aIV);
 
 
            String date = "";
            if(arsi.get(0).getPreparationDate()!=null) {
                System.out.println(arsi.get(0).getPreparationDate().toString() + "]]]]]]]]");
 
                System.out.println(DateUtil.parseCST(arsi.get(0).getPreparationDate().toString()));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                DateTime dat = DateUtil.parseCST(arsi.get(0).getPreparationDate().toString());
                date = new SimpleDateFormat("yyyy-MM-dd").format(dat);
            }
 
 
            String tmpSec = "档号:" +
                    arsi.get(0).getRecordId() +
                    ";档案馆(室)号:" + arsi.get(0).getArchiveRoomNumber()+
                    ";缩微号:" + arsi.get(0).getMicrofilmNumber()+
                    ";发文号:" + arsi.get(0).getInquiryNumber()+
                    ";案卷题名:" + arsi.get(0).getCaseTitle() +
                    ";编制日期:" +  date +
                    ";编制单位:" + arsi.get(0).getPreparationUnit() +
                    ";保管期限:" + arsi.get(0).getRetentionPeriod() +
                    ";密级:" + arsi.get(0).getSecurityClassification();
 
 
            String recordId1 = aIV.getRecordId();
            byte[] imgr1 = barcodeService.generateBarcodeImage(recordId1);
            byte[] sedcode = pdfGenerateService.createQrCodeN(tmpSec, 200, 200);
            ExcelExp e3 = new ExcelExp("案卷封面数据",arsi, ArchiveInfoVo.class);
            ExcelExp e4 = new ExcelExp("案卷封面",  arsi, recordId1, imgr1,sedcode, ArchiveInfoVo.class);
            List<ExcelExp> mysheet1 = new ArrayList<ExcelExp>();
            mysheet1.add(e3);
            mysheet1.add(e4);
            ByteOutputStream bos2 = new ByteOutputStream();
            ExcelUtilManySheetSecond<List<ExcelExp>> util3 = new ExcelUtilManySheetSecond<List<ExcelExp>>(mysheet1);
 
            util3.exportExcelManySheet(bos2, mysheet1);
 
          //  System.out.println(bos2);
            zos.putNextEntry(entryiv);
 
            bos2.writeTo(zos);
 
 
            //pdf目录封面
            String pdfPathF = "07-案卷封面.pdf";
            // pdfGenerateService.generatePdf(pdfPathF, id);
 
            try {
                if (!getLicenseExcel()) {
                    System.out.println("授权失败");
                   // return ;
                }
                // 读取Excel文件
                com.aspose.cells.Workbook wb = poiToAspose(util3.getWb());
 
                // 获取需要导出的sheet(索引从0开始)
                int targetSheetIndex = 1;
                com.aspose.cells.Worksheet targetSheet = wb.getWorksheets().get(targetSheetIndex);
                targetSheet.autoFitRows(true);
                System.out.println("当前sheet名称:" + targetSheet.getName());
                System.out.println("当前sheet索引:" + targetSheet.getIndex());
 
                // 隐藏所有其他工作表
                for (int i = 0; i < wb.getWorksheets().getCount(); i++) {
                    if (i != targetSheetIndex) {
                        wb.getWorksheets().get(i).setVisible(false);
                    }
                }
 
                // 设置活动工作表为目标工作表
                wb.getWorksheets().setActiveSheetIndex(targetSheetIndex);
                // 创建PDF保存选项
                com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
                pdfSaveOptions.setCompliance(com.aspose.cells.PdfCompliance.PDF_A_1_B);
                // 创建临时字节输出流
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
                // 将新的Workbook保存为PDF到临时流
             //   newWorkbook.save(baos, com.aspose.cells.SaveFormat.PDF);
                wb.save(baos, pdfSaveOptions);
 
                // 将PDF添加到ZIP文件
                ZipEntry entry = new ZipEntry(pdfPathF);
                zos.putNextEntry(entry);
                zos.write(baos.toByteArray());
              //  zos.closeEntry();
                // 直接将原始工作簿保存为PDF(只包含可见的工作表)
 
                long now = System.currentTimeMillis();
                //   System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
            } catch (Exception e) {
                e.printStackTrace();
                // 打印详细错误信息
                System.err.println("转换失败:" + e.getMessage());
                e.printStackTrace(System.err);
            }
 
 
 
 
//
//            ByteOutputStream boss = new ByteOutputStream();
//            List<ArchiveInfoVo> aivs = new ArrayList<>();
//            aivs.add(aIV);
//            utilsv.byteOutputStreamExcel(boss, aivs,"Date List", "");
 
                //写入电子目录  xsxl
 
            ZipEntry entry = new ZipEntry("电子文件目录" + ".xls");
            ExcelUtil<DocumentMaterialsVoLarge> util = new ExcelUtil<DocumentMaterialsVoLarge>(DocumentMaterialsVoLarge.class);
 
            zos.putNextEntry(entry);
            ByteOutputStream bos = new ByteOutputStream();
            util.byteOutputStreamExcel(bos, docs,"电子文件目录", "");
            bos.writeTo(zos);
 
            //拿到卷内目录的excel
            List<DocumentMaterialsVoSmall> list2 = dsvs.stream().map(res -> new DocumentMaterialsVoSmall(res.getNum(), res.getDocumentNumber(),res.getCreator(),
                    res.getTitle(), res.getDate(), res.getPageNumberFormatted(), res.getRemarks())).collect(Collectors.toList());
 
            String recordId = dsvs.get(0).getRecordId();
            byte[] imgr = barcodeService.generateBarcodeImage(recordId);
            ExcelExp e1 = new ExcelExp("卷内目录数据",dsvs, DocumentMaterialsVo.class);
            ExcelExp e2 = new ExcelExp("卷内目录", list2, recordId, imgr, DocumentMaterialsVoSmall.class);
            List<ExcelExp> mysheet = new ArrayList<ExcelExp>();
            mysheet.add(e1);
            mysheet.add(e2);
            ExcelUtilManySheet<List<ExcelExp>> util2 = new ExcelUtilManySheet<List<ExcelExp>>(mysheet);
            ZipEntry entr = new ZipEntry("卷内目录" + ".xls");
            ExcelUtil<DocumentMaterialsVo> util1 = new ExcelUtil<DocumentMaterialsVo>(DocumentMaterialsVo.class);
            System.out.println(dsvs);
            zos.putNextEntry(entr);
            ByteOutputStream bos1 = new ByteOutputStream();
 
            util2.exportExcelManySheet(bos1, mysheet);
 
         //   util1.byteOutputStreamExcel(bos1, dsvs,"Date List", "");
            bos1.writeTo(zos);
            //把excel转为pdf
 
            //08-卷内卷内目录的pdf
            String pdf08Path= "08-卷内目录.pdf";
            try {
                if (!getLicenseExcel()) {
                    System.out.println("授权失败");
                    // return ;
                }
                // 读取Excel文件
                com.aspose.cells.Workbook wb1 = poiToAspose(util2.getWb());
 
                // 获取需要导出的sheet(索引从0开始)
                int targetSheetIndex = 1;
                com.aspose.cells.Worksheet targetSheet = wb1.getWorksheets().get(targetSheetIndex);
                targetSheet.autoFitRows(true);
                System.out.println("当前sheet名称:" + targetSheet.getName());
                System.out.println("当前sheet索引:" + targetSheet.getIndex());
 
                // 隐藏所有其他工作表
                for (int i = 0; i < wb1.getWorksheets().getCount(); i++) {
                    if (i != targetSheetIndex) {
                        wb1.getWorksheets().get(i).setVisible(false);
                    }
                }
 
                // 设置活动工作表为目标工作表
                wb1.getWorksheets().setActiveSheetIndex(targetSheetIndex);
                // 创建PDF保存选项
                com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
                pdfSaveOptions.setCompliance(com.aspose.cells.PdfCompliance.PDF_A_1_B);
                // 创建临时字节输出流
                ByteArrayOutputStream baosm = new ByteArrayOutputStream();
 
                // 将新的Workbook保存为PDF到临时流
                //   newWorkbook.save(baos, com.aspose.cells.SaveFormat.PDF);
                wb1.save(baosm, pdfSaveOptions);
 
                // 将PDF添加到ZIP文件
                ZipEntry entry2 = new ZipEntry(pdf08Path);
                zos.putNextEntry(entry2);
                zos.write(baosm.toByteArray());
                //  zos.closeEntry();
                // 直接将原始工作簿保存为PDF(只包含可见的工作表)
 
                long now = System.currentTimeMillis();
                //   System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
            } catch (Exception e) {
                e.printStackTrace();
                // 打印详细错误信息
                System.err.println("转换失败:" + e.getMessage());
                e.printStackTrace(System.err);
            }
 
 
 
 
            //List<DocumentMaterialsVo> list3 = dsvs;
 
 
           // pdfGenerateService.generateFileDirectoryPdf(pdf08Path, list3);
//            ZipEntry zipEntry2 = new ZipEntry(pdf08Path);
//            zos.putNextEntry(zipEntry2);
//
//            // 读取PDF文件内容并写入ZIP
//            try (FileInputStream fis = new FileInputStream(pdf08Path)) {
//                byte[] buffer = new byte[1024];
//                int len;
//                while ((len = fis.read(buffer)) > 0) {
//                    zos.write(buffer, 0, len);
//                }
//            }
 
 
 
 
 
            boolean res = true;
 
            byte[] buf = new byte[1024];
            for (DocumentMaterialsVoLarge dc : docs) {
                String filePath = fileMap.get(dc.getPageNumber().toString());
 
 
//                    else {
//                        // 文件名称
//                        String pname = nams[1];
//
//                        // 拿到图像属性
//                        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
//                        int wid = bufferedImage.getWidth();
//                        int hei = bufferedImage.getHeight();
//                        double sz = Double.parseDouble(String.format("%.2f", file.getSize() * 1.0 / 1024));
//
//                        // 拿到图像的dpi信息
//                        ImageInfo info = Imaging.getImageInfo(file.getBytes());
//                        int wdpi = info.getPhysicalWidthDpi();
//                        int hdpi = info.getPhysicalHeightDpi();
//                        // 计算fileNumber
//                        Long fileNumber = documentMaterialsService.getFiNum(nam, recordId);
//                        // 计算sizeType
//                        String sizeType = getPageSize(wid * hei);
//
//                        // 更新数据库
//                   //     documentMaterialsService.updateByPageNumber(nam, sizeType, fileNumber, wid, hei, wdpi, hdpi, sz, fileName, pname, recordId);
////
////                        urls.add(url);
////                        fileNames.add(fileName);
////                        newFileNames.add(FileUtils.getName(fileName));
////                        originalFilenames.add(fname);
//                    }
//
 
 
                if (filePath == null) {
                    // 补零到4位(根据你的需求调整位数)
                    String paddedKey = frontCompWithZore(4, dc.getPageNumber().intValue());
                    filePath = fileMap.get(paddedKey);
                    System.out.println(paddedKey);
 
                }
                System.out.println(filePath);
 
                if(filePath==null)
                    continue;
 
                if(filePath.contains("profile"))
                    filePath = filePath.replace("/profile/", RuoYiConfig.getProfile() + "/");
 
                File tempFile = new File(filePath);
                System.out.println(filePath);
                System.out.println(tempFile.length());
                //在压缩包中添加文件夹
                if(res) {
                    zos.putNextEntry(new ZipEntry("01-申请材料/"));
                    zos.putNextEntry(new ZipEntry("02-办案过程材料/"));
                    zos.putNextEntry(new ZipEntry("03-结论性文件/"));
                    zos.putNextEntry(new ZipEntry("04-其他材料/"));
                    zos.putNextEntry(new ZipEntry("05-档案变更材料/"));
                    zos.putNextEntry(new ZipEntry("06-业务数据/"));
                    res = false;
                }
                //得到文件名frontCompWithZore(4, dc.get)+
                String fname = "";
             //   if(dc.getFileNumber()!=null&&dc.getPageNumber()!=null) {
 
                    if(dc.getFileNumber()!=null&&dc.getPageNumber()!=null) {
                    //    fname = frontCompWithZore(4, dc.getFileNumber().intValue()) + "-" + dc.getTitle() + "-" + frontCompWithZore(4, dc.getPageNumber().intValue()) + "."
                          //      + filePath.split("\\.")[1];
                    fname = frontCompWithZore(4, dc.getFileNumber().intValue()) +"-" + dc.getTitle() + "-" + frontCompWithZore(4, dc.getPageNumber().intValue()) + "."
                            + filePath.split("\\.")[1];
 
                    System.out.println(fname);
                    if (dc.getStage().equals("01-申请材料"))
                        zos.putNextEntry(new ZipEntry("01-申请材料/" + fname));
                    else if (dc.getStage().equals("02-办案过程材料"))
                        zos.putNextEntry(new ZipEntry("02-办案过程材料/" + fname));
                    else if (dc.getStage().equals("03-结论性文件"))
                        zos.putNextEntry(new ZipEntry("03-结论性文件/" + fname));
                    else if (dc.getStage().equals("04-其他材料")) {
                        zos.putNextEntry(new ZipEntry("04-其他材料/" + fname));
                    } else if (dc.getStage().equals("05-档案变更材料"))
                        zos.putNextEntry(new ZipEntry("05-档案变更材料/" + fname));
                    else if (dc.getStage().equals("06-业务数据"))
                        zos.putNextEntry(new ZipEntry("06-业务数据/" + fname));
                    else
                        zos.putNextEntry(new ZipEntry(fname));
 
                }
 
                int len;
                FileInputStream in = new FileInputStream(tempFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                  //  zos.putNextEntry(new ZipEntry("04-其他材料"));
                zos.closeEntry();
                in.close();
            }
 
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.toString());
            throw new Exception("文件打包:"+e.getMessage());
        }finally {
            //关闭流
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭流
            if(os!= null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
    public String getPageSize(double du)
    {
        if(du <= 8699840 * 1.5)
            return "A4";
        else if(du <= 17403188 * 1.5)
            return "A3";
        else if(du <= 34811347 * 1.5)
            return "A2";
        else if(du <= 69622674 * 1.5)
            return "A1";
        else
            return "A0";
    }
}