feat:文件下载自动压缩功能
This commit is contained in:
+127
-74
@@ -19,6 +19,7 @@ import com.adc.da.report.vo.ReportVo;
|
|||||||
import com.adc.da.util.exception.AdcDaBaseException;
|
import com.adc.da.util.exception.AdcDaBaseException;
|
||||||
import com.adc.da.util.http.ResponseMessage;
|
import com.adc.da.util.http.ResponseMessage;
|
||||||
import com.adc.da.util.http.Result;
|
import com.adc.da.util.http.Result;
|
||||||
|
import com.adc.da.util.utils.CollectionUtils;
|
||||||
import com.adc.da.util.utils.FileUtil;
|
import com.adc.da.util.utils.FileUtil;
|
||||||
import com.adc.da.util.utils.StringUtils;
|
import com.adc.da.util.utils.StringUtils;
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
@@ -39,11 +40,11 @@ import javax.servlet.http.HttpServletRequest;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import javax.validation.Valid;
|
import javax.validation.Valid;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.net.URISyntaxException;
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.text.ParseException;
|
import java.text.ParseException;
|
||||||
import java.text.SimpleDateFormat;
|
import java.text.SimpleDateFormat;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
import static com.adc.da.report.constant.ReportConstants.FILE_EXTENSIONS_PDF;
|
import static com.adc.da.report.constant.ReportConstants.FILE_EXTENSIONS_PDF;
|
||||||
|
|
||||||
@@ -407,105 +408,157 @@ public class ReportManageConroller {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * 下载文件
|
|
||||||
// * @param response
|
|
||||||
// * @param fileId
|
|
||||||
// * @throws IOException
|
|
||||||
// */
|
|
||||||
// @ApiOperation(value = "|下载文件")
|
|
||||||
// @GetMapping("/download")
|
|
||||||
// public void downloadPic(HttpServletResponse response, String fileId) throws IOException {
|
|
||||||
//
|
|
||||||
// try {
|
|
||||||
// FileEntity entity = fileService.getFile(fileId);
|
|
||||||
// String fileName = entity.getFileName();
|
|
||||||
// String filename = URLEncoder.encode(fileName, "UTF-8");
|
|
||||||
// response.setHeader("Content-Disposition", "attachment;filename=" + filename);
|
|
||||||
// response.setContentType("application/x-download");
|
|
||||||
//// File file = new File(uploadFile, entity.getSavePath());
|
|
||||||
// // 上传方式:阿里云:alioss 华为云:hwobs
|
|
||||||
// if ("hwobs".equals(uploadType)){
|
|
||||||
// obsBootUtil.downFile(entity.getSavePath(), response);
|
|
||||||
// }else if ("alioss".equals(uploadType)){
|
|
||||||
// ossClientUtil.downloadFileFromOSS(entity.getSavePath(),response);
|
|
||||||
// }else if ("local".equals(uploadType)){
|
|
||||||
// localFileUtil.downFile(entity.getSavePath(), response);
|
|
||||||
// }
|
|
||||||
// if (FILE_EXTENSIONS_PDF.equalsIgnoreCase(FileUtil.getFileExtension(fileName))) {
|
|
||||||
// String text = "text";
|
|
||||||
// PdfUtil.addWatermarkToPdf(response, text);
|
|
||||||
// }
|
|
||||||
// } catch (Exception ex) {
|
|
||||||
// log.info(ex.getMessage(),ex);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载文件
|
* 下载文件
|
||||||
* @param response
|
* @param response
|
||||||
* @param fileId
|
* @param fileIds
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
@ApiOperation(value = "|下载文件")
|
@ApiOperation(value = "|下载文件")
|
||||||
@GetMapping("/download")
|
@GetMapping("/download")
|
||||||
public void downloadPic(HttpServletResponse response, String fileId,String repostId) throws IOException {
|
public void download(HttpServletResponse response, String[] fileIds, String reportId) throws IOException {
|
||||||
|
List<String> fileIdList = new ArrayList<>();
|
||||||
|
if (CollectionUtils.isNotEmpty(fileIds)) {
|
||||||
|
fileIdList = Arrays.asList(fileIds);
|
||||||
|
}
|
||||||
|
|
||||||
if (StrUtil.isNotBlank(repostId)) {
|
if (StrUtil.isBlank(reportId)) {
|
||||||
|
throw new AdcDaBaseException("缺少报告id");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StrUtil.isNotBlank(reportId)) {
|
||||||
//校验权限
|
//校验权限
|
||||||
if (!reportService.isAllowDownload(UserUtils.getUserId(), repostId)) {
|
if (!reportService.isAllowDownload(UserUtils.getUserId(), reportId)) {
|
||||||
throw new AdcDaBaseException("无此报告下载权限");
|
throw new AdcDaBaseException("无此报告下载权限");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
response.setContentType("application/x-download");
|
||||||
FileEntity entity = fileService.getFile(fileId);
|
//待下载的文件id List
|
||||||
String fileName = entity.getFileName();
|
List<String> downLoadFileIds;
|
||||||
String filename = URLEncoder.encode(fileName, "UTF-8");
|
|
||||||
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
|
|
||||||
response.setContentType("application/x-download");
|
|
||||||
|
|
||||||
//PDF文件需要加水印
|
//判断是从列表页面下载 还是预览页面下载
|
||||||
if (FILE_EXTENSIONS_PDF.equalsIgnoreCase(FileUtil.getFileExtension(fileName))) {
|
if (CollectionUtils.isEmpty(fileIdList)) {
|
||||||
String path = uploadFile + entity.getSavePath();
|
//列表点击下载按钮
|
||||||
FileOutputStream outputStream = new FileOutputStream(path);
|
downLoadFileIds = fileService.getDownloadFileIds(reportId);
|
||||||
// 上传方式:阿里云:alioss 华为云:hwobs
|
if (CollectionUtils.isEmpty(downLoadFileIds)) {
|
||||||
if ("hwobs".equals(uploadType)) {
|
log.info("无法下载,原因可能是无可下载文件(xls/xlsx文件无法下载)");
|
||||||
obsBootUtil.getFileFromOBS(entity.getSavePath(), outputStream);
|
String zipFileName = "empty.zip"; // 压缩文件名
|
||||||
} else if ("alioss".equals(uploadType)) {
|
try {
|
||||||
ossClientUtil.getFileFromOSS(entity.getSavePath(), outputStream);
|
// 设置响应头信息
|
||||||
} else if ("local".equals(uploadType)) {
|
response.setContentType("application/zip");
|
||||||
localFileUtil.getFileFromLocal(entity.getSavePath(), outputStream);
|
response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);
|
||||||
}
|
|
||||||
//给文件添加水印
|
|
||||||
waterMarkUtil.addWatermarkToPdf(new FileInputStream(path), response);
|
|
||||||
|
|
||||||
} else {
|
// 创建空的ZipOutputStream
|
||||||
// 上传方式:阿里云:alioss 华为云:hwobs 本地:local
|
ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
|
||||||
if ("hwobs".equals(uploadType)){
|
zipOutputStream.close();
|
||||||
obsBootUtil.downFile(entity.getSavePath(), response);
|
return;
|
||||||
}else if ("alioss".equals(uploadType)){
|
} catch (IOException e) {
|
||||||
ossClientUtil.downloadFileFromOSS(entity.getSavePath(),response);
|
e.printStackTrace();
|
||||||
}else if ("local".equals(uploadType)){
|
|
||||||
localFileUtil.downFile(entity.getSavePath(), response);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
} catch (Exception ex) {
|
//检测是否要下载Excel文件
|
||||||
log.info(ex.getMessage(),ex);
|
if (fileService.hasExcelFileId(fileIdList)) {
|
||||||
|
throw new AdcDaBaseException("不可以下载Excel文件");
|
||||||
|
}
|
||||||
|
//预览点击下载按钮
|
||||||
|
downLoadFileIds = fileIdList;
|
||||||
}
|
}
|
||||||
if (StringUtils.isNotEmpty(repostId)){
|
|
||||||
|
//如果只下载一个文件,则不压缩
|
||||||
|
if (downLoadFileIds.size() == 1) {
|
||||||
|
String fileId = downLoadFileIds.get(0);
|
||||||
|
try {
|
||||||
|
FileEntity entity = fileService.getFile(fileId);
|
||||||
|
String fileName = entity.getFileName();
|
||||||
|
// 获取编码后的文件名
|
||||||
|
String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
|
||||||
|
response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
|
||||||
|
|
||||||
|
//PDF文件需要加水印
|
||||||
|
if (FILE_EXTENSIONS_PDF.equalsIgnoreCase(FileUtil.getFileExtension(fileName))) {
|
||||||
|
String path = uploadFile + entity.getSavePath();
|
||||||
|
FileOutputStream outputStream = new FileOutputStream(path);
|
||||||
|
// 上传方式:阿里云:alioss 华为云:hwobs
|
||||||
|
if ("hwobs".equals(uploadType)) {
|
||||||
|
obsBootUtil.getFileFromOBS(entity.getSavePath(), outputStream);
|
||||||
|
} else if ("alioss".equals(uploadType)) {
|
||||||
|
ossClientUtil.getFileFromOSS(entity.getSavePath(), outputStream);
|
||||||
|
} else if ("local".equals(uploadType)) {
|
||||||
|
localFileUtil.getFileFromLocal(entity.getSavePath(), outputStream);
|
||||||
|
}
|
||||||
|
//给文件添加水印
|
||||||
|
waterMarkUtil.addWatermarkToPdfAndWriteToResponse(new FileInputStream(path), response);
|
||||||
|
outputStream.close();
|
||||||
|
} else {
|
||||||
|
// 上传方式:阿里云:alioss 华为云:hwobs 本地:local
|
||||||
|
if ("hwobs".equals(uploadType)){
|
||||||
|
obsBootUtil.downFile(entity.getSavePath(), response);
|
||||||
|
}else if ("alioss".equals(uploadType)){
|
||||||
|
ossClientUtil.downloadFileFromOSS(entity.getSavePath(),response);
|
||||||
|
}else if ("local".equals(uploadType)){
|
||||||
|
localFileUtil.downFile(entity.getSavePath(), response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
log.info(ex.getMessage(),ex);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
List<String> filePaths = new ArrayList<>();
|
||||||
|
String reportName = reportDao.selectById(reportId).getName() + ".zip";
|
||||||
|
// 获取编码后的文件名
|
||||||
|
String encodedFileName = URLEncoder.encode(reportName, "UTF-8");
|
||||||
|
// 设置响应头信息
|
||||||
|
response.setContentType("application/zip");
|
||||||
|
response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
|
||||||
|
response.setHeader("Content-Transfer-Encoding", "binary");
|
||||||
|
response.setHeader("Pragma", "public");
|
||||||
|
response.setHeader("Cache-Control", "no-store");
|
||||||
|
response.setHeader("Expires", "0");
|
||||||
|
|
||||||
|
for (String fileId : downLoadFileIds) {
|
||||||
|
try {
|
||||||
|
FileEntity entity = fileService.getFile(fileId);
|
||||||
|
String fileName = entity.getFileName();
|
||||||
|
|
||||||
|
String path = uploadFile + entity.getSavePath();
|
||||||
|
FileOutputStream outputStream = new FileOutputStream(path);
|
||||||
|
filePaths.add(path);
|
||||||
|
|
||||||
|
// 上传方式:阿里云:alioss 华为云:hwobs
|
||||||
|
if ("hwobs".equals(uploadType)) {
|
||||||
|
obsBootUtil.getFileFromOBS(entity.getSavePath(), outputStream);
|
||||||
|
} else if ("alioss".equals(uploadType)) {
|
||||||
|
ossClientUtil.getFileFromOSS(entity.getSavePath(), outputStream);
|
||||||
|
} else if ("local".equals(uploadType)) {
|
||||||
|
localFileUtil.getFileFromLocal(entity.getSavePath(), outputStream);
|
||||||
|
}
|
||||||
|
//PDF文件需要加水印
|
||||||
|
if (FILE_EXTENSIONS_PDF.equalsIgnoreCase(FileUtil.getFileExtension(fileName))) {
|
||||||
|
waterMarkUtil.savePdfToFile(new FileInputStream(path), path);
|
||||||
|
}
|
||||||
|
outputStream.close();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
log.info(ex.getMessage(),ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//将文件压缩 写入Response
|
||||||
|
localFileUtil.compressFiles(filePaths, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StringUtils.isNotEmpty(reportId)){
|
||||||
ReportLogBook reportLog = new ReportLogBook();
|
ReportLogBook reportLog = new ReportLogBook();
|
||||||
reportLog.setId(UUID.randomUUID().toString().replaceAll("-",""));
|
reportLog.setId(UUID.randomUUID().toString().replaceAll("-",""));
|
||||||
reportLog.setReportId(repostId);
|
reportLog.setReportId(reportId);
|
||||||
reportLog.setType(2);
|
reportLog.setType(2);
|
||||||
reportLog.setUpdateTime(new Date());
|
reportLog.setUpdateTime(new Date());
|
||||||
reportLog.setUserId(UserUtils.getUserId());
|
reportLog.setUserId(UserUtils.getUserId());
|
||||||
reportLogBookDao.insert(reportLog);
|
reportLogBookDao.insert(reportLog);
|
||||||
|
|
||||||
//报告日志管理
|
//报告日志管理
|
||||||
ReportEntity reportEntity = reportDao.selectById(repostId);
|
ReportEntity reportEntity = reportDao.selectById(reportId);
|
||||||
reportLog(reportEntity.getName(),"下载");
|
reportLog(reportEntity.getName(),"下载");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,12 @@ package com.adc.da.report.dao.mysql;
|
|||||||
import com.adc.da.report.eo.FileEntity;
|
import com.adc.da.report.eo.FileEntity;
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @Author doudxw
|
* @Author doudxw
|
||||||
* @Date 2021/6/28 15:19
|
* @Date 2021/6/28 15:19
|
||||||
*/
|
*/
|
||||||
public interface FileDao extends BaseMapper<FileEntity> {
|
public interface FileDao extends BaseMapper<FileEntity> {
|
||||||
|
List<String> getDownloadFileIds(String reportId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,5 +28,19 @@ public interface IFileService {
|
|||||||
|
|
||||||
List<Map<String, Object>> batchUploadFile(MultipartFile[] files);
|
List<Map<String, Object>> batchUploadFile(MultipartFile[] files);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断传进来的fileIds里有没有Excel的fileId
|
||||||
|
* @param fileIds
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
boolean hasExcelFileId(List<String> fileIds);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据报告id返回所有可以下载的文件id
|
||||||
|
* @param reportId
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
List<String> getDownloadFileIds(String reportId);
|
||||||
|
|
||||||
Map<String, Object> uploadFile(MultipartFile file);
|
Map<String, Object> uploadFile(MultipartFile file);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
package com.adc.da.report.service.impl;
|
package com.adc.da.report.service.impl;
|
||||||
|
|
||||||
|
import com.adc.da.report.constant.ReportConstants;
|
||||||
import com.adc.da.report.dao.mysql.FileDao;
|
import com.adc.da.report.dao.mysql.FileDao;
|
||||||
import com.adc.da.report.eo.FileEntity;
|
import com.adc.da.report.eo.FileEntity;
|
||||||
import com.adc.da.report.service.IFileService;
|
import com.adc.da.report.service.IFileService;
|
||||||
import com.adc.da.report.util.LocalFileUtil;
|
import com.adc.da.report.util.LocalFileUtil;
|
||||||
import com.adc.da.report.util.OSSClientUtil;
|
import com.adc.da.report.util.OSSClientUtil;
|
||||||
import com.adc.da.report.util.ObsBootUtil;
|
import com.adc.da.report.util.ObsBootUtil;
|
||||||
|
import com.adc.da.util.utils.CollectionUtils;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import lombok.Synchronized;
|
import lombok.Synchronized;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@@ -175,4 +178,27 @@ public class IFileServiceImpl implements IFileService {
|
|||||||
this.addFile(entity);
|
this.addFile(entity);
|
||||||
return resultMap;
|
return resultMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean hasExcelFileId(List<String> fileIds) {
|
||||||
|
boolean hasExcelFileId = false;
|
||||||
|
LambdaQueryWrapper<FileEntity> fileEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
|
||||||
|
fileEntityLambdaQueryWrapper.in(FileEntity::getFileId, fileIds);
|
||||||
|
List<FileEntity> fileEntities = fileDao.selectList(fileEntityLambdaQueryWrapper);
|
||||||
|
if (CollectionUtils.isNotEmpty(fileEntities)) {
|
||||||
|
for (FileEntity fileEntity : fileEntities) {
|
||||||
|
if (ReportConstants.FILE_EXTENSIONS_XLS.equals(fileEntity.getFileType()) ||
|
||||||
|
ReportConstants.FILE_EXTENSIONS_XLSX.equals(fileEntity.getFileType())) {
|
||||||
|
hasExcelFileId = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hasExcelFileId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> getDownloadFileIds(String reportId) {
|
||||||
|
return fileDao.getDownloadFileIds(reportId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ import javax.servlet.http.HttpServletResponse;
|
|||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Caihaohan
|
* @author Caihaohan
|
||||||
@@ -24,6 +27,39 @@ public class LocalFileUtil {
|
|||||||
@Value("${localFilePath}")
|
@Value("${localFilePath}")
|
||||||
private String localFilePath;
|
private String localFilePath;
|
||||||
|
|
||||||
|
public void compressFiles(List<String> filePaths, HttpServletResponse response) {
|
||||||
|
try {
|
||||||
|
// 创建输出流
|
||||||
|
OutputStream outputStream = response.getOutputStream();
|
||||||
|
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
|
||||||
|
|
||||||
|
byte[] buffer = new byte[1024];
|
||||||
|
|
||||||
|
for (String filePath : filePaths) {
|
||||||
|
File sourceFile = new File(filePath);
|
||||||
|
|
||||||
|
ZipEntry zipEntry = new ZipEntry(sourceFile.getName());
|
||||||
|
zipOutputStream.putNextEntry(zipEntry);
|
||||||
|
|
||||||
|
FileInputStream fileInputStream = new FileInputStream(sourceFile);
|
||||||
|
|
||||||
|
int len;
|
||||||
|
while ((len = fileInputStream.read(buffer)) > 0) {
|
||||||
|
zipOutputStream.write(buffer, 0, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
fileInputStream.close();
|
||||||
|
zipOutputStream.closeEntry();
|
||||||
|
}
|
||||||
|
|
||||||
|
zipOutputStream.close();
|
||||||
|
|
||||||
|
System.out.println("文件成功压缩成ZIP格式并写入 HttpServletResponse!");
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void saveFile(InputStream fileInputStream, String fileName) throws IOException {
|
public void saveFile(InputStream fileInputStream, String fileName) throws IOException {
|
||||||
String path = localFilePath + fileName;
|
String path = localFilePath + fileName;
|
||||||
FileOutputStream fileOutputStream = new FileOutputStream(path);
|
FileOutputStream fileOutputStream = new FileOutputStream(path);
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import javax.annotation.Resource;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.awt.*;
|
import java.awt.*;
|
||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
@@ -52,49 +53,62 @@ public class WaterMarkUtil {
|
|||||||
return configValue + " " + userName + " " + formattedDate;
|
return configValue + " " + userName + " " + formattedDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addWatermarkToPdf(FileInputStream inputStream, HttpServletResponse response) throws IOException {
|
public PDDocument addWatermarkToPdf(FileInputStream inputStream) throws IOException {
|
||||||
String watermarkText = getWaterMarkConfig();
|
String watermarkText = getWaterMarkConfig();
|
||||||
// 加载PDF文档
|
PDDocument document = PDDocument.load(inputStream);
|
||||||
try (PDDocument document = PDDocument.load(inputStream)) {
|
|
||||||
// 设置水印字体、字体大小、颜色和透明度
|
|
||||||
ClassPathResource fontResource = new ClassPathResource("fonts/SourceHanSerif-VF.ttf");
|
|
||||||
PDType0Font font = PDType0Font.load(document, fontResource.getInputStream());
|
|
||||||
float fontSize = 13.0f;
|
|
||||||
Color color = new Color(100, 100, 100, 0);
|
|
||||||
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
|
|
||||||
graphicsState.setNonStrokingAlphaConstant(0.4f);
|
|
||||||
graphicsState.setStrokingAlphaConstant(0.4f);
|
|
||||||
|
|
||||||
// 遍历每一页并添加水印
|
// 设置水印字体、字体大小、颜色和透明度
|
||||||
for (PDPage page : document.getPages()) {
|
ClassPathResource fontResource = new ClassPathResource("fonts/SourceHanSerif-VF.ttf");
|
||||||
// 获取页面尺寸以计算水印位置
|
PDType0Font font = PDType0Font.load(document, fontResource.getInputStream());
|
||||||
PDRectangle pageSize = page.getMediaBox();
|
float fontSize = 13.0f;
|
||||||
float xStep = pageSize.getWidth() / 4;
|
Color color = new Color(100, 100, 100, 0);
|
||||||
float yStep = pageSize.getHeight() / 4;
|
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
|
||||||
float rotationInRadians = (float) Math.toRadians(20);
|
graphicsState.setNonStrokingAlphaConstant(0.4f);
|
||||||
|
graphicsState.setStrokingAlphaConstant(0.4f);
|
||||||
|
|
||||||
for (float xPosition = pageSize.getLowerLeftX(); xPosition <= pageSize.getWidth(); xPosition += xStep) {
|
// 遍历每一页并添加水印
|
||||||
for (float yPosition = pageSize.getLowerLeftY(); yPosition <= pageSize.getHeight(); yPosition += yStep) {
|
for (PDPage page : document.getPages()) {
|
||||||
// 创建内容流并设置图形状态参数
|
// 获取页面尺寸以计算水印位置
|
||||||
try (PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
|
PDRectangle pageSize = page.getMediaBox();
|
||||||
contentStream.setGraphicsStateParameters(graphicsState);
|
float xStep = pageSize.getWidth() / 4;
|
||||||
contentStream.setFont(font, fontSize);
|
float yStep = pageSize.getHeight() / 4;
|
||||||
contentStream.setNonStrokingColor(color);
|
float rotationInRadians = (float) Math.toRadians(20);
|
||||||
contentStream.beginText();
|
|
||||||
contentStream.setRenderingMode(RenderingMode.FILL);
|
for (float xPosition = pageSize.getLowerLeftX(); xPosition <= pageSize.getWidth(); xPosition += xStep) {
|
||||||
// 设置水印文本的旋转和位置
|
for (float yPosition = pageSize.getLowerLeftY(); yPosition <= pageSize.getHeight(); yPosition += yStep) {
|
||||||
contentStream.setTextMatrix(Matrix.getRotateInstance(rotationInRadians, xPosition, yPosition));
|
// 创建内容流并设置图形状态参数
|
||||||
contentStream.showText(watermarkText);
|
try (PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
|
||||||
contentStream.endText();
|
contentStream.setGraphicsStateParameters(graphicsState);
|
||||||
}
|
contentStream.setFont(font, fontSize);
|
||||||
|
contentStream.setNonStrokingColor(color);
|
||||||
|
contentStream.beginText();
|
||||||
|
contentStream.setRenderingMode(RenderingMode.FILL);
|
||||||
|
// 设置水印文本的旋转和位置
|
||||||
|
contentStream.setTextMatrix(Matrix.getRotateInstance(rotationInRadians, xPosition, yPosition));
|
||||||
|
contentStream.showText(watermarkText);
|
||||||
|
contentStream.endText();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
return document;
|
||||||
|
}
|
||||||
|
|
||||||
// 将处理后的PDF写入HTTP响应
|
|
||||||
try (OutputStream outputStream = response.getOutputStream()) {
|
public void savePdfToFile(FileInputStream inputStream, String outputPath) throws IOException {
|
||||||
document.save(outputStream);
|
PDDocument pdDocument = addWatermarkToPdf(inputStream);
|
||||||
}
|
try (FileOutputStream outputStream = new FileOutputStream(outputPath)) {
|
||||||
|
pdDocument.save(outputStream);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void addWatermarkToPdfAndWriteToResponse(FileInputStream inputStream, HttpServletResponse response) throws IOException {
|
||||||
|
PDDocument document = addWatermarkToPdf(inputStream);
|
||||||
|
try (OutputStream outputStream = response.getOutputStream()) {
|
||||||
|
document.save(outputStream);
|
||||||
|
}
|
||||||
|
document.close();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE mapper
|
||||||
|
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||||
|
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
|
<mapper namespace="com.adc.da.report.dao.mysql.FileDao">
|
||||||
|
|
||||||
|
<select id="getDownloadFileIds" resultType="string">
|
||||||
|
SELECT
|
||||||
|
f.FILE_ID
|
||||||
|
FROM
|
||||||
|
`ts_file` AS f
|
||||||
|
LEFT JOIN ts_report_file AS rf ON f.FILE_ID = rf.file_id
|
||||||
|
WHERE
|
||||||
|
rf.report_id = #{reportId}
|
||||||
|
AND
|
||||||
|
f.FILE_TYPE != "xls"
|
||||||
|
AND
|
||||||
|
f.FILE_TYPE != "xlsx"
|
||||||
|
</select>
|
||||||
|
</mapper>
|
||||||
Reference in New Issue
Block a user