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