Просмотр исходного кода

下载pdf、excel时,先检查是否存在有效的文件,若无,先生成

sunyj 9 лет назад
Родитель
Сommit
19f16d2b42

+ 62 - 23
src/main/java/com/uas/report/controller/PrintController.java

@@ -1,8 +1,10 @@
 package com.uas.report.controller;
 
 import java.io.File;
+import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.OutputStream;
+import java.util.HashMap;
 import java.util.Map;
 
 import javax.servlet.ServletException;
@@ -115,12 +117,45 @@ public class PrintController {
 			exportFileType = "pdf";
 		}
 
-		byte[] data = printService.export(userName, reportName, whereCondition, otherParameters, exportFileType);
-		String message = "";
-		if (ArrayUtils.isEmpty(data)) {
-			message = "报表导出失败:" + reportName;
-			logger.error(message);
-			throw new SystemError(message);
+		byte[] data = null;
+
+		String filePath = ReportConstants.GENERATED_FILES_PATH
+				+ printService.generateFileName(userName, reportName, whereCondition, otherParameters);
+		if (exportFileType.equals("xls_with_only_data")) {
+			filePath += ".xls";
+		} else {
+			filePath += "." + exportFileType;
+		}
+		File file = new File(PathUtils.getAppPath() + filePath);
+		// 文件无效(不存在或过期),创建
+		if (!printService.isFileValid(file.getPath())) {
+			data = printService.export(userName, reportName, whereCondition, otherParameters, exportFileType);
+			String message = "";
+			if (ArrayUtils.isEmpty(data)) {
+				message = "报表导出失败:" + reportName;
+				logger.error(message);
+				throw new SystemError(message);
+			}
+			printService.writeDataToFile(file.getPath(), data);
+		} else {
+			FileInputStream fileInputStream = null;
+			try {
+				fileInputStream = new FileInputStream(file);
+				data = new byte[fileInputStream.available()];
+				fileInputStream.read(data);
+			} catch (IOException e) {
+				e.printStackTrace();
+				throw new SystemError(e.getMessage());
+			} finally {
+				if (fileInputStream != null) {
+					try {
+						fileInputStream.close();
+					} catch (IOException e) {
+						e.printStackTrace();
+						throw new SystemError(e.getMessage());
+					}
+				}
+			}
 		}
 
 		try {
@@ -162,29 +197,33 @@ public class PrintController {
 	public Map<String, Object> loadPdfData(String userName, String reportName, String whereCondition,
 			String otherParameters, Integer pageIndex, HttpServletResponse response) {
 		checkParameters(userName, reportName);
-
 		logger.info("开始预览报表:" + reportName);
-		Map<String, Object> result = printService.preview(userName, reportName, whereCondition, otherParameters,
-				pageIndex);
-		byte[] data = null;
-		if (result != null && result.containsKey("data")) {
-			data = (byte[]) result.remove("data");
-		}
-		String message = "";
-		if (data == null) {
-			message = "获取预览数据失败";
-			logger.error(message);
-			throw new SystemError(message);
-		}
+		Map<String, Object> result = null;
 
+		// 相对路径,返回给前端
 		String pdfPath = ReportConstants.GENERATED_FILES_PATH
 				+ printService.generateFileName(userName, reportName, whereCondition, otherParameters) + ".pdf";
 		File file = new File(PathUtils.getAppPath() + pdfPath);
-		// 文件过期或不存在,重新创建pdf文件
-		if (printService.isFileExpired(file)) {
-			printService.writePdfFile(file.getPath(), data);
+		// 文件无效(不存在或过期),重新创建pdf文件
+		if (!printService.isFileValid(file.getPath())) {
+			result = printService.preview(userName, reportName, whereCondition, otherParameters, pageIndex);
+			byte[] data = null;
+			if (result != null && result.containsKey("data")) {
+				data = (byte[]) result.remove("data");
+			}
+			String message = "";
+			if (data == null) {
+				message = "获取预览数据失败";
+				logger.error(message);
+				throw new SystemError(message);
+			}
+			printService.writeDataToFile(file.getPath(), data);
+			// 同时生成分页的pdf
+			printService.writePagedPdfFiles(file.getPath());
+		} else {
+			result = new HashMap<>();
+			result.put("pageSize", printService.getPageSize(file.getPath()));
 		}
-
 		result.put("pdfPath", pdfPath);
 		logger.info("预览报表成功:" + reportName);
 		return result;

+ 27 - 10
src/main/java/com/uas/report/service/PrintService.java

@@ -1,6 +1,5 @@
 package com.uas.report.service;
 
-import java.io.File;
 import java.util.Map;
 
 /**
@@ -50,15 +49,33 @@ public interface PrintService {
 			String otherParameters, Integer pageIndex);
 
 	/**
-	 * 预览 时将pdf文件先写入本地,再将其路径返回给前台
+	 * 利用字节数组数据创建文件
 	 * 
-	 * @param absolutePath
+	 * @param filePath
 	 *            要写入的文件的绝对路径
 	 * @param data
-	 *            pdf文件的数据
+	 *            文件的数据
 	 * @return
 	 */
-	public void writePdfFile(String absolutePath, byte[] data);
+	public void writeDataToFile(String filePath, byte[] data);
+
+	/**
+	 * 利用给定的pdf文件在同级目录下生成多个分页的pdf文件(一页对应一个文件)
+	 * 
+	 * @param pdfFilePath
+	 *            给定的pdf文件绝对路径
+	 * @return
+	 */
+	public void writePagedPdfFiles(String pdfFilePath);
+
+	/**
+	 * 获取给定的pdf文件的页数
+	 * 
+	 * @param pdfFilePath
+	 *            给定的pdf文件绝对路径
+	 * @return pdf文件的页数
+	 */
+	public int getPageSize(String pdfFilePath);
 
 	/**
 	 * 根据报表名、账套名等生成文件名
@@ -77,11 +94,11 @@ public interface PrintService {
 	public String generateFileName(String userName, String reportName, String whereCondition, String otherParameters);
 
 	/**
-	 * 判断文件是否过期(文件不存在视为过期)
+	 * 判断文件是否有效(文件存在并且未过有效期)
 	 * 
-	 * @param file
-	 *            所指定的文件
-	 * @return 是否过期
+	 * @param filePath
+	 *            所指定的文件绝对路径
+	 * @return 是否有效
 	 */
-	public boolean isFileExpired(File file);
+	public boolean isFileValid(String filePath);
 }

+ 51 - 41
src/main/java/com/uas/report/service/impl/PrintServiceImpl.java

@@ -87,26 +87,57 @@ public class PrintServiceImpl implements PrintService {
 	}
 
 	@Override
-	public void writePdfFile(String absolutePath, byte[] data) {
-		File pdfFile = new File(absolutePath);
-		if (!pdfFile.getParentFile().exists()) {
-			pdfFile.getParentFile().mkdirs();
+	public void writeDataToFile(String filePath, byte[] data) {
+		File file = new File(filePath);
+		if (!file.getParentFile().exists()) {
+			file.getParentFile().mkdirs();
 		}
 
 		try {
-			FileOutputStream fos = new FileOutputStream(pdfFile);
+			FileOutputStream fos = new FileOutputStream(file);
 			fos.write(data);
 			fos.flush();
-			logger.info("Generated pdf file: " + pdfFile.getPath());
+			logger.info("Write file..." + file.getPath());
 			fos.close();
-			// 同时生成分页的pdf
-			writePagedPdfFiles(pdfFile.getPath());
+		} catch (IOException e) {
+			e.printStackTrace();
+			throw new SystemError(e.getMessage());
+		}
+	}
+
+	@Override
+	public void writePagedPdfFiles(String pdfFilePath) {
+		try {
+			PdfReader pdfReader = new PdfReader(pdfFilePath);
+			for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
+				Document document = new Document();
+				FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath.replace(".pdf", "_" + i + ".pdf"));
+				PdfCopy pdfCopy = new PdfCopy(document, fileOutputStream);
+				document.open();
+				// 原pdf文件的每一页生成新的pdf
+				pdfCopy.addPage(pdfCopy.getImportedPage(pdfReader, i));
+				pdfCopy.close();
+				// 不关闭,生成的pdf无法正常打开
+				document.close();
+				fileOutputStream.close();
+			}
+			pdfReader.close();
 		} catch (IOException | DocumentException e) {
 			e.printStackTrace();
 			throw new SystemError(e.getMessage());
 		}
 	}
 
+	@Override
+	public int getPageSize(String pdfFilePath) {
+		try {
+			return new PdfReader(pdfFilePath).getNumberOfPages();
+		} catch (IOException e) {
+			e.printStackTrace();
+			throw new SystemError(e.getMessage());
+		}
+	}
+
 	@Override
 	public String generateFileName(String userName, String reportName, String whereCondition, String otherParameters) {
 		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(reportName)) {
@@ -124,41 +155,20 @@ public class PrintServiceImpl implements PrintService {
 	}
 
 	@Override
-	public boolean isFileExpired(File file) {
-		if (file != null && file.exists()) {
-			long interval = new Date().getTime() - file.lastModified();
-			// 剩余的有效期(最高为5分钟)
-			long validity = 5 * 60 * 1000 - interval;
-			if (validity > 0) {
-				logger.info(file.getName() + " will be expired after " + validity / 1000.0 + "s");
-				return false;
+	public boolean isFileValid(String filePath) {
+		if (!StringUtils.isEmpty(filePath)) {
+			File file = new File(filePath);
+			if (file.exists()) {
+				long interval = new Date().getTime() - file.lastModified();
+				// 剩余的有效期(最高为5分钟)
+				long validity = 5 * 60 * 1000 - interval;
+				if (validity > 0) {
+					logger.info(file.getName() + " will be expired after " + validity / 1000.0 + "s");
+					return true;
+				}
 			}
 		}
-		return true;
-	}
-
-	/**
-	 * 将给定的pdf文件生成多个分页的文件
-	 * 
-	 * @param pdfFilePath
-	 *            指定的pdf文件路径
-	 * @throws IOException
-	 * @throws DocumentException
-	 */
-	private void writePagedPdfFiles(String pdfFilePath) throws IOException, DocumentException {
-		PdfReader pdfReader = new PdfReader(pdfFilePath);
-		for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
-			Document document = new Document();
-			FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath.replace(".pdf", "_" + i + ".pdf"));
-			PdfCopy pdfCopy = new PdfCopy(document, fileOutputStream);
-			document.open();
-			// 原pdf文件的每一页生成新的pdf
-			pdfCopy.addPage(pdfCopy.getImportedPage(pdfReader, i));
-			pdfCopy.close();
-			// 不关闭,生成的pdf无法正常打开
-			document.close();
-			fileOutputStream.close();
-		}
+		return false;
 	}
 
 	/**