fei
1 天以前 e899d2709f21b322232fb64778fef296233be3f0
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
package com.ruoyi.web.controller.archive;
 
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.domain.DocumentMaterials;
import com.ruoyi.domain.vo.ArchiveInfoVo;
import com.ruoyi.domain.vo.DocumentMaterialsVo;
import com.ruoyi.framework.web.domain.server.Sys;
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.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
 
import static org.apache.poi.hssf.usermodel.HSSFCell.*;
 
@RestController
@RequestMapping("/system/archiveAllExport")
public class archiveAllExportController {
 
    @Autowired
    private pdfGenerateService pdfGenerateService;
    @Autowired
    private BarcodeService barcodeService;
    @Autowired
    private IDocumentMaterialsService documentMaterialsService;
 
    @Autowired
    private IArchiveRecordsService iArchiveRecordsService;
    /**
     * 打包下载
     * @param response
     * @param
     */
    @PostMapping("/export")
 
    public void packDownload(HttpServletResponse response, Long id) throws Exception {
        // 获取文件的保存位置,读取数据库,
        DocumentMaterials documentMaterials = new DocumentMaterials();
        documentMaterials.setRecordId(id);
        List<DocumentMaterials> docs = documentMaterialsService.selectDocumentMaterialsList(documentMaterials);
        List<DocumentMaterialsVo> dsvs = documentMaterialsService.findArchMInfo(id.toString());
        ArchiveInfoVo aIV = iArchiveRecordsService.selectByRecordId(id);
 
        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;
            File file = compressedFileToZip(docs, dsvs, aIV);
            System.out.println(file.getName());
            //输出文件流
            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;
 
 
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, realFileName);
        FileUtils.writeBytes(filePath, response.getOutputStream());
        //        FileInputStream inputStream = new FileInputStream(file);
//        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型.
//        response.setContentType("application/octet-stream");
//        //2.设置文件头:最后一个参数是设置下载文件名
//        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//        response.addHeader("Content-Length", "" + file.length());
//
//        //3.通过response获取ServletOutputStream对象(out)
//        ServletOutputStream out = response.getOutputStream();
//
//        int b = 0;
//        byte[] buffer = new byte[1024];
//        while (b != -1) {
//            b = inputStream.read(buffer);
//            //4.写到输出流(out)中
//            out.write(buffer, 0, b);
//        }
//        out.flush();
//        out.close();
//        inputStream.close();
    }
    public String frontCompWithZore(int formatLength,int formatNumber){
        /**
         * 0 指前面补充零
         * formatLength 字符总长度为 formatLength
         * inputNumber 格式化数字
         * d 代表为正数。
         */
        String newString = String.format("%0"+formatLength+"d", formatNumber);
        return newString;
    }
 
    private void handleXSSFImages(XSSFSheet sheet, Document pdfDoc) throws Exception {
        XSSFDrawing drawing = sheet.getDrawingPatriarch();
        if (drawing == null) return;
 
        for (XSSFShape shape : drawing.getShapes()) {
            if (shape instanceof XSSFPicture) {
                XSSFPicture pic = (XSSFPicture)shape;
                XSSFClientAnchor anchor = pic.getPreferredSize();
 
                // 获取图片数据
                byte[] bytes = pic.getPictureData().getData();
                Image pdfImage = Image.getInstance(bytes);
 
                // 设置图片位置和大小
                float imageWidth = pdfImage.getWidth();
                float imageHeight = pdfImage.getHeight();
                float scale = Math.min(
                        (PageSize.A4.getWidth() - 100) / imageWidth,
                        (PageSize.A4.getHeight() - 100) / imageHeight
                );
                pdfImage.scaleAbsolute(imageWidth * scale, imageHeight * scale);
 
                // 添加图片到PDF
                pdfDoc.add(pdfImage);
                pdfDoc.add(Chunk.NEWLINE);
            }
        }
    }
 
 
 
 
    private static String getCellValue(Cell cell,FormulaEvaluator evaluator) {
      //  System.out.println(cell);
        if (cell == null) return "";
        CellValue cellValue = evaluator.evaluate(cell);
        if(cellValue==null)
            return "";
      //  System.out.println(cellValue.getCellType());
        switch (cellValue.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                // 获取数值并转为整型
                double numericValue = cell.getNumericCellValue();
                // 判断是否为整数
                if (numericValue == (int)numericValue) {
                    if((int)numericValue==0)
                        return "";
                    else
                        return String.valueOf((int)numericValue);
                } else {
                    return String.valueOf(numericValue); // 或者根据需要返回四舍五入的整型
                }
 
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
 
                return cell.getCellFormula()+"";
            case BLANK:
                return "";
            default:
                return "";
        }
    }
    private int getRealLastCellNum(Row row) {
        int lastCellNum = 0;
        for (int i = 0; i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            if (cell != null && cell.getCellType() != CellType.BLANK) {
                lastCellNum = i + 1;
            }
        }
        return lastCellNum;
    }
 
 
 
 
    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<DocumentMaterials> docs, List<DocumentMaterialsVo> dsvs,   ArchiveInfoVo aIV) throws Exception {
        //压缩包具体名称(拼接时间戳防止重名)
        String datumName = "";
        String zipFileName = datumName + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".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);
 
            //pdf目录封面
            String pdfPathF = "07-卷面封面.pdf";
            pdfGenerateService.generatePdf(pdfPathF);
            // 2. 压缩PDF到ZIP文件
                // 添加PDF文件到ZIP
                ZipEntry zipEntry = new ZipEntry(pdfPathF);
                zos.putNextEntry(zipEntry);
 
                // 读取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);
                    }
                }
                //excel 卷内封面导出zip
            ZipEntry entryiv = new ZipEntry("卷内封面" + ".xls");
            ExcelUtil<ArchiveInfoVo> utilsv = new ExcelUtil<ArchiveInfoVo>(ArchiveInfoVo.class);
 
            zos.putNextEntry(entryiv);
            ByteOutputStream boss = new ByteOutputStream();
            List<ArchiveInfoVo> aivs = new ArrayList<>();
            aivs.add(aIV);
            utilsv.byteOutputStreamExcel(boss, aivs,"Date List", "");
            boss.writeTo(zos);
                //写入电子目录  xsxl
 
            ZipEntry entry = new ZipEntry("电子文件目录" + ".xls");
            ExcelUtil<DocumentMaterials> util = new ExcelUtil<DocumentMaterials>(DocumentMaterials.class);
 
            zos.putNextEntry(entry);
            ByteOutputStream bos = new ByteOutputStream();
            util.byteOutputStreamExcel(bos, docs,"Date List", "");
            bos.writeTo(zos);
 
            //拿到卷内目录的excel
            ZipEntry entr = new ZipEntry("卷内目录" + ".xls");
            ExcelUtil<DocumentMaterialsVo> util1 = new ExcelUtil<DocumentMaterialsVo>(DocumentMaterialsVo.class);
            System.out.println(dsvs);
            zos.putNextEntry(entr);
            ByteOutputStream bos1 = new ByteOutputStream();
            util1.byteOutputStreamExcel(bos1, dsvs,"Date List", "");
            bos1.writeTo(zos);
            //把excel转为pdf
 
 
            try {
                // 1. 读取Excel文件
                String excelPath = RuoYiConfig.getProfile() + "/download/"+"卷內目录.xls";
                String pdfPath = RuoYiConfig.getProfile() + "/download/"+"1.pdf";
 
                Workbook workbook = WorkbookFactory.create(new File(excelPath));
                FileOutputStream fos = new FileOutputStream(pdfPath);
                FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
 
 
                // 获取第一个工作表
                    Sheet sheet = workbook.getSheetAt(1);
 
                    // 创建PDF文档对象
                    Document document = new Document(PageSize.A2, 50, 50, 50, 50);
 
                    // 创建PDF输出流
                    PdfWriter writer = PdfWriter.getInstance(document, fos);
                // 4. 处理工作表中的图片
                if (workbook instanceof XSSFWorkbook) {
                    handleXSSFImages((XSSFSheet)sheet, document);
                }
                    // 打开PDF文档
                    document.open();
 
                    // 创建PDF表格对象
                System.out.println(sheet.getRow(0).getLastCellNum()+"--00");
                    PdfPTable table = new PdfPTable(sheet.getRow(0).getLastCellNum());
                    table.setHeaderRows(1);
 
                    // 设置表格宽度
                    table.setWidthPercentage(100);
 
                    // 设置表格标题
                    Paragraph title = new Paragraph(sheet.getSheetName(), new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 16, Font.BOLD));
                    title.setAlignment(Element.ALIGN_CENTER);
                    document.add(title);
                   // System.out.println(sheet.)
                    // 添加表格内容
                    for (Row row : sheet) {
                        {
                            if (row == null) continue;
                            System.out.println(getRealLastCellNum(row)+"---987");
//                            if(row.getRowNum()==0)
//                                continue;
                            if(row.getRowNum()==2)
                            {
                                PdfPCell pdfCell = ImageSet(100);
                                pdfCell.setColspan(7);
                                pdfCell.setRowspan(3);
                                pdfCell.setBorderWidth(1f);
                                pdfCell.setBorderColor(BaseColor.BLACK);
                                pdfCell.setPadding(5f);
                                pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                                table.addCell(pdfCell);
                                System.out.println("{{{{{{{{{{{{{");
                                continue;
                            }
                            for (int i = 0; i < 7; i++)
                            {
 
                                Cell cell = row.getCell(i);
                                if(row.getRowNum()==3)
                                {
                                    PdfPCell pdfCell = new PdfPCell(new Paragraph("卷内目录", new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 12)));
                                    pdfCell.setColspan(7);
                                    pdfCell.setBorderWidth(1f);
                                    pdfCell.setBorderColor(BaseColor.BLACK);
                                    pdfCell.setPadding(5f);
                                    pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                                    table.addCell(pdfCell);
                                    System.out.println("{{{{{{{{{{{{{");
                                    break;
                                }
                                if(cell==null) {
 
                                    table.addCell("");
                                    continue;
                                }
                                PdfPCell pdfCell = new PdfPCell(new Paragraph(getCellValue(cell, evaluator), new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 12)));
 
                                if(row.getRowNum()!=1) {
                                    pdfCell.setBorderWidth(1f);
                                    pdfCell.setBorderColor(BaseColor.BLACK);
                                    pdfCell.setPadding(5f);
                                    pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                                }
                                if (cell.getRowIndex() == 5) {
                                    pdfCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                                }
 
                                table.addCell(pdfCell);
 
                            }
                        }
                    }
 
                    // 添加表格到PDF文档
                    table.setSpacingBefore(20f);
                    table.setSpacingAfter(20f);
                    table.setKeepTogether(true);
                    document.add(table);
 
                    // 关闭PDF文档
                    document.close();
 
 
 
 
 
            } catch (Exception e) {
                e.printStackTrace();
            }
            boolean res = true;
 
            byte[] buf = new byte[1024];
            for (DocumentMaterials dc : docs) {
                String filePath = dc.getUrl();
                filePath = filePath.replace("/profile/", RuoYiConfig.getProfile() + "/");
 
                System.out.println(filePath);
                File tempFile = new File(filePath);
                //在压缩包中添加文件夹
                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 = frontCompWithZore(4, dc.getFileNumber().intValue())+"-"+dc.getTitle()+"-"+frontCompWithZore(4,dc.getPageNumber().intValue())+"."
                        +dc.getUrl().split("\\.")[1];
                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;
    }
 
}