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 docs = documentMaterialsService.selectDocumentMaterialsList(documentMaterials); List dsvs = documentMaterialsService.findArchMInfo(id.toString()); ArchiveInfoVo aIV = iArchiveRecordsService.selectByRecordId(id); List 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 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 docs, List 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 utilsv = new ExcelUtil(ArchiveInfoVo.class); zos.putNextEntry(entryiv); ByteOutputStream boss = new ByteOutputStream(); List aivs = new ArrayList<>(); aivs.add(aIV); utilsv.byteOutputStreamExcel(boss, aivs,"Date List", ""); boss.writeTo(zos); //写入电子目录 xsxl ZipEntry entry = new ZipEntry("电子文件目录" + ".xls"); ExcelUtil util = new ExcelUtil(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 util1 = new ExcelUtil(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; } }