增加word文档(excel,ppt和word)转pdf的接口

This commit is contained in:
weiweiw 2024-08-22 14:46:31 +08:00
parent 7965be04f4
commit 144e391a6f
3 changed files with 116 additions and 26 deletions

View File

@ -36,4 +36,5 @@ public interface FilePreview {
String filePreviewHandle(String url, Model model, FileAttribute fileAttribute);
String fileConvert(String url, Model model, FileAttribute fileAttribute);
default String wordConvertPdf(String url, FileAttribute fileAttribute) {return "不支持的文件类型转换";};
}

View File

@ -19,9 +19,15 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
@ -175,4 +181,73 @@ public class OfficeFilePreviewImpl implements FilePreview {
}
}
@Override
public String wordConvertPdf(String url,FileAttribute fileAttribute){
// 预览Type参数传了就取参数的没传取系统默认
long startime = System.currentTimeMillis();
String officePreviewType = fileAttribute.getOfficePreviewType();
boolean userToken = fileAttribute.getUsePasswordCache();
String baseUrl = BaseUrlFilter.getBaseUrl();
String suffix = fileAttribute.getSuffix(); //获取文件后缀
String fileName = fileAttribute.getName(); //获取文件原始名称
String filePassword = fileAttribute.getFilePassword(); //获取密码
boolean forceUpdatedCache=fileAttribute.forceUpdatedCache(); //是否启用强制更新命令
boolean isHtmlView = false; //xlsx 转换成html
String cacheName = fileAttribute.getCacheName(); //转换后的文件名
String outFilePath = fileAttribute.getOutFilePath(); //转换后生成文件的路径
String suffix1 = KkFileUtils.suffixFromFileName(cacheName);
//将excel文档格式不转换为html而是转换为pdf
if (suffix1.equals("html") ){
cacheName = cacheName.substring(0, cacheName.lastIndexOf(".")+1) + "pdf";
outFilePath = outFilePath.substring(0, outFilePath.lastIndexOf(".")+1) + "pdf";
}
//如果有同名文件就默认为已经转换
if (KkFileUtils.isExist(outFilePath)) {
fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath));
return baseUrl + cacheName;
}
long endtime = System.currentTimeMillis();
System.out.println("下载前耗时:" + (endtime - startime) / 1000 + "ms");
startime = System.currentTimeMillis();
if (forceUpdatedCache|| !fileHandlerService.listConvertedFiles().containsKey(cacheName) || !ConfigConstants.isCacheEnabled()) {
// 下载远程文件到本地如果文件在本地已存在不会重复下载
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
if (response.isFailure()) {
return response.getMsg();
}
String filePath = response.getContent();
boolean isPwdProtectedOffice = OfficeUtils.isPwdProtected(filePath); // 判断是否加密文件
if (isPwdProtectedOffice && !StringUtils.hasLength(filePassword)) {
// 加密文件需要密码
return "加密文件需要密码";
} else {
if (StringUtils.hasText(outFilePath)) {
try {
logger.info("start to officeToPdfService.openOfficeToPDF");
officeToPdfService.openOfficeToPDF(filePath, outFilePath, fileAttribute);
logger.info("end to officeToPdfService.openOfficeToPDF");
} catch (OfficeException e) {
if (isPwdProtectedOffice && !OfficeUtils.isCompatible(filePath, filePassword)) {
// 加密文件密码错误提示重新输入
return "加密文件密码错误";
}
return "抱歉,该文件版本不兼容,文件版本错误";
}
//是否保留OFFICE源文件
if (!fileAttribute.isCompressFile() && ConfigConstants.getDeleteSourceFile()) {
KkFileUtils.deleteFileByPath(filePath);
}
if (userToken || !isPwdProtectedOffice) {
// 加入缓存
fileHandlerService.addConvertedFile(cacheName, fileHandlerService.getRelativePath(outFilePath));
}
}
}
}
return baseUrl + cacheName;
}
}

View File

@ -88,6 +88,14 @@ public class OnlinePreviewController {
return filePreview.filePreviewHandle(fileUrl, model, fileAttribute); //统一在这里处理 url
}
/**
* 转换文件用于大文件在预览前的转换
* @param url
* @param model
* @param req
* @param token
* @return
*/
@GetMapping( "/onConvert")
@ResponseBody
public String onConvert(String url, Model model, HttpServletRequest req, String token) {
@ -113,32 +121,38 @@ public class OnlinePreviewController {
return filePreview.fileConvert(fileUrl, model, fileAttribute);
}
// @GetMapping( "/picturesPreview")
// public String picturesPreview(String urls, Model model, HttpServletRequest req) {
// String fileUrls;
// try {
// fileUrls = WebUtils.decodeUrl(urls);
// // 防止XSS攻击
// fileUrls = KkFileUtils.htmlEscape(fileUrls);
// } catch (Exception ex) {
// String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "urls");
// return otherFilePreview.notSupportedFile(model, errorMsg);
// }
// logger.info("预览文件url{}urls{}", fileUrls, urls);
// // 抽取文件并返回文件列表
// String[] images = fileUrls.split("\\|");
// List<String> imgUrls = Arrays.asList(images);
// model.addAttribute("imgUrls", imgUrls);
// String currentUrl = req.getParameter("currentUrl");
// if (StringUtils.hasText(currentUrl)) {
// String decodedCurrentUrl = new String(Base64.decodeBase64(currentUrl));
// decodedCurrentUrl = KkFileUtils.htmlEscape(decodedCurrentUrl); // 防止XSS攻击
// model.addAttribute("currentUrl", decodedCurrentUrl);
// } else {
// model.addAttribute("currentUrl", imgUrls.get(0));
// }
// return PICTURE_FILE_PREVIEW_PAGE;
// }
/**
* 转换文件用于大文件在预览前的转换
* @param url
// * @param model
* @param req
* @param token
* @return
*/
@GetMapping( "/onConvertPdf")
@ResponseBody
public String onConvertPdf(String url, HttpServletRequest req, String token) {
String fileUrl;
try {
if (!WebUtils.checkToken(token)) {
return "token 错误";
}
fileUrl = WebUtils.decodeUrl(url);
} catch (Exception ex) {
String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "url");
return errorMsg;
}
FileAttribute fileAttribute = fileHandlerService.getFileAttribute(fileUrl, req); //这里不在进行URL 处理了
FilePreview filePreview = previewFactory.get(fileAttribute);
logger.info("转换文件url{}previewType{}", fileUrl, fileAttribute.getType());
fileUrl =WebUtils.urlEncoderencode(fileUrl);
if (ObjectUtils.isEmpty(fileUrl)) {
return "非法路径,不允许访问";
}
return filePreview.wordConvertPdf(fileUrl, fileAttribute);
}
/**
* 根据url获取文件内容