package com.jq.web.controller.common;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itextpdf.text.pdf.PdfReader;
import com.jq.common.config.JqConfig;
import com.jq.common.core.domain.BaseEntity;
import com.jq.common.core.domain.entity.SysAttachmentInfo;
import com.jq.common.utils.DateUtils;
import com.jq.common.utils.EmptyUtil;
import com.jq.common.utils.RotateImage;
import com.jq.common.utils.WordToPdfUtil;
import com.jq.common.utils.file.FileUploadUtils;
import com.jq.common.utils.pdf.PdfUtil;
import com.jq.common.utils.poi.CustomXWPFDocument;
import com.jq.project.domain.BaseCompanyUserCertFile;
import com.jq.project.domain.HighProductCertFile;
import com.jq.project.domain.HighResultCertFile;
import com.jq.project.mapper.BaseCompanyUserCertFileMapper;
import com.jq.project.mapper.HighProductCertFileMapper;
import com.jq.project.mapper.HighResultCertFileMapper;
import com.jq.system.mapper.SysAttachmentInfoMapper;
import com.jq.system.service.SysAttachmentInfoService;
import com.lowagie.text.exceptions.InvalidPdfException;
import com.zhuozhengsoft.pageoffice.OfficeVendorType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.List;
@Component
public class BaseFileController {
protected final Logger logger = LoggerFactory.getLogger(BaseFileController.class);
@Autowired
private SysAttachmentInfoService sysAttachmentInfoService;
@Autowired
private SysAttachmentInfoMapper sysAttachmentInfoMapper;
@Autowired
private HighProductCertFileMapper highProductCertFileMapper;
@Autowired
private HighResultCertFileMapper highResultCertFileMapper;
@Autowired
private BaseCompanyUserCertFileMapper baseCompanyUserCertFileMapper;
@Autowired
private JqConfig jqConfig;
//100 -500 dpi
private static int dpi = 230;
/**
* 创建唯一的附件数据。 返回附件实例对象。
*
* @param relatePage
* @param relateKey
* @param relateId
* @param fileOrgName
* @return
* @throws Exception
*/
public SysAttachmentInfo genDocxFilePath(String relatePage, String relateKey, Long relateId, String fileOrgName, int fileSize) throws Exception {
JqConfig jqConfig = new JqConfig();
String diskPath = jqConfig.getDisk() + jqConfig.getUploadPath();
//清除相关数据
sysAttachmentInfoService.deleteByRelate(relatePage, relateKey, relateId);
String extension = "docx";
SysAttachmentInfo sysAttachmentInfo = new SysAttachmentInfo();
sysAttachmentInfo.setRelatePage(relatePage);
sysAttachmentInfo.setRelateKey(relateKey);
sysAttachmentInfo.setRelateId(relateId);
sysAttachmentInfo.setFileOrgName(fileOrgName);
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + extension;
String filePath = DateUtils.datePath();
sysAttachmentInfo.setFilePath(filePath + "/");
String location = filePath + "/" + fileName;
String savePath = diskPath + filePath;
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
sysAttachmentInfo.setFileType(extension);
sysAttachmentInfo.setLocation(location); // 相对路径
sysAttachmentInfo.setFileName(fileName);
sysAttachmentInfo.setFileSize(FileUploadUtils.getPrintSize(fileSize));
sysAttachmentInfo.setFileOrgName(fileOrgName);
sysAttachmentInfo.setRelateId(relateId);
sysAttachmentInfo.setUploadDate(new Date());
sysAttachmentInfo.setDelFlag("0");
sysAttachmentInfo.setUploadType("1"); //本地上传
// sysAttachmentInfo.setCreateBy(SecurityUtils.getUserName());
sysAttachmentInfo.setCreateTime(new Date());
Long attachId = sysAttachmentInfoService.insertSysattach(sysAttachmentInfo).getId();
sysAttachmentInfo.setId(attachId);
return sysAttachmentInfo;
}
/**
* @description 产品说明书将word转成pdf
* @author liuxj
* @date 2023/2/21 0021
*/
public SysAttachmentInfo wordToPdfFile(SysAttachmentInfo sysAttachmentInfo) throws Exception {
JqConfig jqConfig = new JqConfig();
//清除相关数据
sysAttachmentInfoService.deleteByRelate(sysAttachmentInfo.getRelatePage(), sysAttachmentInfo.getRelateKey(), sysAttachmentInfo.getRelateId());
String diskPath = jqConfig.getDisk() + jqConfig.getUploadPath();
String extension = "pdf";
SysAttachmentInfo attachmentInfo = new SysAttachmentInfo();
attachmentInfo.setRelatePage(sysAttachmentInfo.getRelatePage());
attachmentInfo.setRelateKey(sysAttachmentInfo.getRelateKey());
attachmentInfo.setRelateId(sysAttachmentInfo.getRelateId());
attachmentInfo.setFileOrgName(sysAttachmentInfo.getFileOrgName().replace(".docx", ".pdf"));
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + extension;
String filePath = DateUtils.datePath();
attachmentInfo.setFilePath(filePath + "/");
String location = filePath + "/" + fileName;
String savePath = diskPath + filePath;
WordToPdfUtil.word2pdf(diskPath + sysAttachmentInfo.getLocation(), savePath + "/" + fileName);
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
attachmentInfo.setFileType(extension);
attachmentInfo.setLocation(location); // 相对路径
attachmentInfo.setFileName(fileName);
attachmentInfo.setUploadDate(new Date());
attachmentInfo.setDelFlag("0");
attachmentInfo.setUploadType("1"); //本地上传
attachmentInfo.setCreateTime(new Date());
Long attachId = sysAttachmentInfoService.insertSysattach(attachmentInfo).getId();
attachmentInfo.setId(attachId);
return attachmentInfo;
}
public <T> List<String> genImgListFormAttach(List<T> list, String relateKey) throws Exception {
List<SysAttachmentInfo> attachList = new ArrayList<>();
for (Object obj : list) {
BaseEntity baseEntity = (BaseEntity) obj;
List<SysAttachmentInfo> sysAttachmentInfoList = baseEntity.getAttachmentList();
for (SysAttachmentInfo sysAttachmentInfo : sysAttachmentInfoList) {
if (sysAttachmentInfo.getRelateKey().equals(relateKey)) {
attachList.add(sysAttachmentInfo);
}
}
}
//启用多线程, pdfImgList 转成 img List
List<String> imgPathList = attachToImgList(attachList);
return imgPathList;
}
public <T> List<SysAttachmentInfo> genAttachListFormAttach(List<T> list, String relateKey) throws Exception {
List<SysAttachmentInfo> attachList = new ArrayList<>();
for (Object obj : list) {
BaseEntity baseEntity = (BaseEntity) obj;
List<SysAttachmentInfo> sysAttachmentInfoList = baseEntity.getAttachmentList();
for (SysAttachmentInfo sysAttachmentInfo : sysAttachmentInfoList) {
if (sysAttachmentInfo.getRelateKey().equals(relateKey)) {
attachList.add(sysAttachmentInfo);
}
}
}
return attachList;
}
/**
* sysAttachmentInfo pdf 转 imgPathList
*
* @param sysAttachmentInfo
* @return
*/
public List<String> attachToImgList(SysAttachmentInfo sysAttachmentInfo) throws Exception {
List<SysAttachmentInfo> sysAttachmentInfoList = new ArrayList<>();
sysAttachmentInfoList.add(sysAttachmentInfo);
return attachToImgList(sysAttachmentInfoList);
}
/**
* pdf 文件列表转移
*
* @param
* @return
*/
public List<String> attachToImgList(List<SysAttachmentInfo> attachList) throws Exception {
final String path = jqConfig.getDisk() + jqConfig.getUploadPath();
final String tempPath = jqConfig.getDisk() + jqConfig.getFolder() + DateUtils.datePath() + "/";
final List<String> imgPathList = new ArrayList<>();
String[] fileTypeArr = {"pdf", "png", "jpg", "jpeg", "PDF"};
List<String> fileTypeList = Arrays.asList(fileTypeArr);
//先校验,增加效率
for (SysAttachmentInfo sysAttachmentInfo : attachList) {
String filePath = path + sysAttachmentInfo.getLocation();
if (!new File(filePath).exists()) {
throw new Exception("文件不存在: " + (null == sysAttachmentInfo.getFileBase() ? "" : sysAttachmentInfo.getFileBase()) + sysAttachmentInfo.getFileOrgName() + "," + sysAttachmentInfo.getLocation() + "!");
}
if (!fileTypeList.contains(sysAttachmentInfo.getFileType())) {
throw new Exception("文件类型不支持: " + sysAttachmentInfo.getFileName() + "," + sysAttachmentInfo.getLocation() + "!");
}
if ("pdf".equals(sysAttachmentInfo.getFileType()) || "PDF".equals(sysAttachmentInfo.getFileType())) {
try {
PdfReader reader = new PdfReader(filePath);
reader.unethicalreading = true; // 新加这段代码, 就能将密码报错问题解决
} catch (InvalidPdfException e) {
throw new Exception("文件无法解密: " + sysAttachmentInfo.getFileName() + "," + sysAttachmentInfo.getFilePath() + "!");
} catch (Exception e) {
e.printStackTrace();
throw new Exception("PDF解析错误: " + sysAttachmentInfo.getFileName() + "," + sysAttachmentInfo.getFilePath() + "!");
}
}
}
//获取上传的所有附件
for (SysAttachmentInfo sysAttachmentInfo : attachList) {
String filePath = path + sysAttachmentInfo.getLocation();
logger.info("【PDF转IMG】执行文件" + sysAttachmentInfo.getFileOrgName());
if (sysAttachmentInfo.getFileType().equals("pdf")) {
if (EmptyUtil.isNullOrEmpty(sysAttachmentInfo.getImgFilePath())) {
// 未解析图片
String imgFilePath = sysAttachmentInfo.getLocation().split(".pdf")[0];
int imgFileSize = PdfUtil.pdf2Png(path + sysAttachmentInfo.getLocation(), path + imgFilePath, dpi);
sysAttachmentInfo.setImgFilePath(imgFilePath);
sysAttachmentInfo.setImgFileSize(Long.valueOf(imgFileSize));
sysAttachmentInfoMapper.updateByPrimaryKeySelective(sysAttachmentInfo);
}
//拼接图片数据到imgPathList
for (long i = 1; i <= sysAttachmentInfo.getImgFileSize(); i++) {
String imgPath = path + sysAttachmentInfo.getImgFilePath() + "/" + i + ".png";
imgPathList.add(imgPath);
}
} else if (sysAttachmentInfo.getFileType().equals("PDF")) {
if (EmptyUtil.isNullOrEmpty(sysAttachmentInfo.getImgFilePath())) {
// 未解析图片
String imgFilePath = sysAttachmentInfo.getLocation().split(".PDF")[0];
int imgFileSize = PdfUtil.pdf2Png(path + sysAttachmentInfo.getLocation(), path + imgFilePath, dpi);
sysAttachmentInfo.setImgFilePath(imgFilePath);
sysAttachmentInfo.setImgFileSize(Long.valueOf(imgFileSize));
sysAttachmentInfoMapper.updateByPrimaryKeySelective(sysAttachmentInfo);
}
//拼接图片数据到imgPathList
for (long i = 1; i <= sysAttachmentInfo.getImgFileSize(); i++) {
String imgPath = path + sysAttachmentInfo.getImgFilePath() + "/" + i + ".png";
imgPathList.add(imgPath);
}
} else if (sysAttachmentInfo.getFileType().equals("png") || sysAttachmentInfo.getFileType().equals("jpg") || sysAttachmentInfo.getFileType().equals("jpeg")) {
imgPathList.add(filePath);
}
}
return formatImgList(imgPathList);
}
/**
* @Description: pdfToImgList
* @Author: xzl
* @Date: 2023/5/15 10:49
*/
public List<String> pdfToImgList(String pdfPath) throws Exception {
if (!new File(pdfPath).exists()) {
throw new Exception("文件不存在!");
}
final List<String> imgPathList = new ArrayList<>();
String imgFilePath = pdfPath.split(".pdf")[0];
int imgFileSize = PdfUtil.pdf2Png(pdfPath, imgFilePath, dpi);
//拼接图片数据到imgPathList
for (long i = 1; i <= imgFileSize; i++) {
String imgPath = imgFilePath + "/" + i + ".png";
imgPathList.add(imgPath);
}
return formatImgList(imgPathList);
}
public <T> List<String> genImgListFormCertFile(List<T> list) throws Exception {
List<BaseEntity> baseEntityList = new ArrayList<>();
for (Object obj : list) {
BaseEntity baseEntity = (BaseEntity) obj;
baseEntityList.add(baseEntity);
}
//启用多线程, pdfImgList 转成 img List
List<String> imgPathList = certToImgList(baseEntityList);
return imgPathList;
}
/**
* pdf 文件列表转移
*
* @param
* @return
*/
public List<String> certToImgList(List<BaseEntity> baseEntityList) throws Exception {
final String path = jqConfig.getDisk() + jqConfig.getUploadPath();
final List<String> imgPathList = new ArrayList<>();
String[] fileTypeArr = {"pdf", "png", "jpg", "jpeg", "PDF"};
List<String> fileTypeList = Arrays.asList(fileTypeArr);
//文件校验
for (BaseEntity certFileEntity : baseEntityList) {
String filePath = path + certFileEntity.getFilePath();
if (!new File(filePath).exists()) {
throw new Exception("文件不存在: " + (null == certFileEntity.getFileBase() ? "" : certFileEntity.getFileBase()) + certFileEntity.getFileName() + "," + certFileEntity.getFilePath() + "!");
}
if (!fileTypeList.contains(certFileEntity.getFileType())) {
throw new Exception("文件类型不支持: " + certFileEntity.getFileName() + "," + certFileEntity.getFilePath() + "!");
}
if ("pdf".equals(certFileEntity.getFileType())) {
try {
PdfReader reader = new PdfReader(filePath);
reader.unethicalreading = true; // 新加这段代码, 就能将密码报错问题解决
} catch (InvalidPdfException e) {
throw new Exception("文件无法解密: " + certFileEntity.getFileName() + "," + certFileEntity.getFilePath() + "!");
} catch (Exception e) {
e.printStackTrace();
throw new Exception("PDF解析错误: " + certFileEntity.getFileName() + "," + certFileEntity.getFilePath() + "!");
}
}
}
//获取上传的所有附件
for (BaseEntity certFileEntity : baseEntityList) {
logger.info("【PDF转IMG】执行文件" + certFileEntity.getFileName());
String filePath = path + certFileEntity.getFilePath();
if (certFileEntity.getFileType().equals("pdf")) {
if (HighProductCertFile.class.equals(certFileEntity.getClass())) {
//科技成果材料
HighProductCertFile highProductCertFile = (HighProductCertFile) certFileEntity;
if (EmptyUtil.isNullOrEmpty(highProductCertFile.getImgFilePath())) {
// 未解析图片
String imgFilePath = highProductCertFile.getFilePath().split(".pdf")[0];
int imgFileSize = PdfUtil.pdf2Png(filePath, path + imgFilePath, dpi);
highProductCertFile.setImgFilePath(imgFilePath);
highProductCertFile.setImgFileSize(Long.valueOf(imgFileSize));
highProductCertFileMapper.updateByPrimaryKeySelective(highProductCertFile);
}
//拼接图片数据到imgPathList
for (long i = 1; i <= highProductCertFile.getImgFileSize(); i++) {
String imgPath = path + highProductCertFile.getImgFilePath() + "/" + i + ".png";
imgPathList.add(imgPath);
}
} else if (HighResultCertFile.class.equals(certFileEntity.getClass())) {
//证明文件材料
HighResultCertFile highResultCertFile = (HighResultCertFile) certFileEntity;
if (EmptyUtil.isNullOrEmpty(highResultCertFile.getImgFilePath())) {
// 未解析图片
String imgFilePath = highResultCertFile.getFilePath().split(".pdf")[0];
int imgFileSize = PdfUtil.pdf2Png(filePath, path + imgFilePath, dpi);
highResultCertFile.setImgFilePath(imgFilePath);
highResultCertFile.setImgFileSize(Long.valueOf(imgFileSize));
highResultCertFileMapper.updateByPrimaryKeySelective(highResultCertFile);
}
//拼接图片数据到imgPathList
for (long i = 1; i <= highResultCertFile.getImgFileSize(); i++) {
String imgPath = path + highResultCertFile.getImgFilePath() + "/" + i + ".png";
imgPathList.add(imgPath);
}
} else if (BaseCompanyUserCertFile.class.equals(certFileEntity.getClass())) {
//证明文件材料
BaseCompanyUserCertFile userCertFile = (BaseCompanyUserCertFile) certFileEntity;
if (EmptyUtil.isNullOrEmpty(userCertFile.getImgFilePath())) {
// 未解析图片
String imgFilePath = userCertFile.getFilePath().split(".pdf")[0];
int imgFileSize = PdfUtil.pdf2Png(filePath, path + imgFilePath, dpi);
userCertFile.setImgFilePath(imgFilePath);
userCertFile.setImgFileSize(Long.valueOf(imgFileSize));
baseCompanyUserCertFileMapper.updateByPrimaryKeySelective(userCertFile);
}
//拼接图片数据到imgPathList
for (long i = 1; i <= userCertFile.getImgFileSize(); i++) {
String imgPath = path + userCertFile.getImgFilePath() + "/" + i + ".png";
imgPathList.add(imgPath);
}
}
} else if (certFileEntity.getFileType().equals("png") || certFileEntity.getFileType().equals("jpg") || certFileEntity.getFileType().equals("jpeg")) {
imgPathList.add(filePath);
}
}
return formatImgList(imgPathList);
}
/**
* 格式化图片尺寸,将长宽比大于1的图片 重新转档存储 ,位置不变
*
* @return
*/
public List<String> formatImgList(List<String> imgPathList) throws Exception {
final String tempPath = jqConfig.getDisk() + jqConfig.getFolder() + DateUtils.datePath() + "/";
File folder = new File(tempPath);
if (!folder.exists()) {
folder.mkdirs();
}
List<String> reImgList = new ArrayList<>();
for (String path : imgPathList) {
File file = new File(path);
BufferedImage image = ImageIO.read(file);
// 宽度
int width = image.getWidth();
// 高度
int height = image.getHeight();
logger.info("该解析文件的长宽比," + width + ":" + height);
if (width - height > 0) {
String imgFilePath = tempPath + UUID.randomUUID().toString().replaceAll("-", "") + ".png";
File newFile = new File(imgFilePath);
image = RotateImage.Rotate(image, 270);
ImageIO.write(image, "png", newFile);
reImgList.add(imgFilePath);
} else {
reImgList.add(path);
}
}
return reImgList;
}
public void insertImgToDoc(String docPath, String regionName, List<String> imgPath) throws Exception {
new CustomXWPFDocument().runImg(docPath, regionName, imgPath);
}
public void insertImgListToDoc(String docPath, String regionName, List<String> imgPathList) throws Exception {
long startTime = System.currentTimeMillis(); //获取开始时间
logger.info("Img插入Docx【正在执行】:" + imgPathList.size() + "张," + docPath);
new CustomXWPFDocument().runImg(docPath, regionName, imgPathList);
long endTime = System.currentTimeMillis(); //获取结束时间
logger.info("Img插入Docx【运行时间】: " + (endTime - startTime) / 1000 + "s"); //主要运行时间在磁盘保存时间较慢 图片尺寸较大
logger.info("Img插入Docx【完成】:" + imgPathList.size() + "张");
}
public void updateFileSize(SysAttachmentInfo sysAttachmentInfo) throws Exception {
if (!EmptyUtil.isNullOrEmpty(sysAttachmentInfo)) {
String filePath = jqConfig.getDisk() + jqConfig.getUploadPath();
File file = new File(filePath + sysAttachmentInfo.getLocation());
sysAttachmentInfo.setFileSize(FileUploadUtils.getPrintSize(file.length()));
sysAttachmentInfoService.saveOrUpdate(sysAttachmentInfo);
}
}
/**
* proportion 裁减比例 1代表裁剪百分之一
*/
public List<String> cutImg(List<String> imagePath, int proportion) throws Exception {
List<String> saveList = new ArrayList<>();
String tempPath = jqConfig.getDisk() + jqConfig.getFolder() + LocalDate.now() + "/";
for (String imageName : imagePath) {
// 读取原图
File sourcePic = new File(imageName);
try {
BufferedImage sourceImage = ImageIO.read(sourcePic);
int width = sourceImage.getWidth();
int height = sourceImage.getHeight();
// 边框裁减比例
int cutWidth = width * proportion / 100;
int cutHeight = height * proportion / 100;
// 左上角为原点 左边框多裁剪 右边框少裁剪 上下等比例裁剪
BufferedImage subImage = sourceImage.getSubimage(cutWidth * 6 / 5, cutHeight * 3 / 5, width - cutWidth * 2, height - cutHeight * 2);
// 输出图片
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".png";
File targetImage = new File(tempPath + fileName);
if (!targetImage.exists()) {
targetImage.mkdirs();
}
ImageIO.write(subImage, "png", targetImage);
saveList.add(tempPath + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
return saveList;
}
/**
* 设置office默认类型
*
* @param poCtrl
* @param officeType 0/null 自动选择 1 WPS 2 Office
*/
public void setOfficeType(PageOfficeCtrl poCtrl, String officeType) {
//客户端启动wps打开文件
if (EmptyUtil.isNullOrEmpty(officeType)) {
poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect); //自动启动客户机上最先安装的Office软件
} else if ("1".equals(officeType)) {
poCtrl.setOfficeVendor(OfficeVendorType.WPSOffice); //客户端启动wps打开文件
} else if ("2".equals(officeType)) {
poCtrl.setOfficeVendor(OfficeVendorType.MSOffice); //客户端启动word打开文件(默认值)
} else {
poCtrl.setOfficeVendor(OfficeVendorType.AutoSelect); //自动启动客户机上最先安装的Office软件
}
}
}