您现在的位置是:首页 >学无止境 >kkFileView二开之word转pdf接口网站首页学无止境
kkFileView二开之word转pdf接口
简介kkFileView二开之word转pdf接口
kkFileView二开之word转pdf接口
1 kkFileView源码下载及编译
前文 【kkFileView二开之源码编译及部署】 已完成了kkFileView源码二开的基础准备。
2 word转pdf接口
2.1 背景
在实际工作过程中,经常会有系统针对word模板填充,并转换为pdf的需求,如合同、订单等文件,在代码内集成word转pdf一方面代码会比较臃肿,另一方面兼容性相较于kkfile会差一点。
在使用kkFileView的过程中,在线浏览word文档界面上可以以pdf的方式进行预览,因而想到可以使用kkFileView对外提供接口,传入指定的word文件后,将该文件转换为pdf后返回,通过阅读kkFileView源码后,发现可以实现,故编写该文档。
2.2 接口开发
在cn.keking.web.controller包下,新增ConvertController.java 文件
package cn.keking.web.controller;
import cn.keking.config.ConfigConstants;
import cn.keking.model.FileAttribute;
import cn.keking.model.FileType;
import cn.keking.model.ReturnResponse;
import cn.keking.service.FileHandlerService;
import cn.keking.service.OfficeToPdfService;
import cn.keking.utils.DownloadUtils;
import cn.keking.utils.KkFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* 文件转换接口
*/
@Controller
public class ConvertController {
private final String fileDir = ConfigConstants.getFileDir();
//临时目录
private final String tempPath = "temp" + File.separator;
@Autowired
private OfficeToPdfService officeToPdfService;
@Autowired
private FileHandlerService fileHandlerService;
private static final String FILE_DIR = ConfigConstants.getFileDir();
/**
* 转换文件并输出
* @param rep
* @param fileAttribute
* @param filePath
*/
private void coverAndWrite(HttpServletResponse rep,FileAttribute fileAttribute,String filePath){
String covertFilePath = "";
try{
String fileName = fileAttribute.getName().replace(fileAttribute.getSuffix(),"pdf");
covertFilePath = FILE_DIR+ fileName;
//调用kkfile服务进行转换
officeToPdfService.openOfficeToPDF(filePath, covertFilePath, fileAttribute);
rep.setContentType("application/octet-stream");
rep.setHeader("Content-Disposition", "attachment; filename="" + fileName + """);
// 创建输出流
ServletOutputStream outStream = rep.getOutputStream();
try (InputStream in = new BufferedInputStream(Files.newInputStream(Paths.get(covertFilePath)))) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
} finally {
outStream.flush();
outStream.close();
}
}catch (Exception e){
e.printStackTrace();
}finally {
//完成后,删除文件
File file = new File(filePath);
file.deleteOnExit();
file = new File(covertFilePath);
file.deleteOnExit();
}
}
/**
* 使用链接将文件转换为pdf
* @param fileUrl
* @param req
* @param rep
* @throws Exception
*/
@GetMapping("/word2Pdf")
public void word2Pdf(String fileUrl, HttpServletRequest req, HttpServletResponse rep) throws Exception{
if(null == fileUrl || fileUrl.equals("")){
throw new Exception("文件路径不能为空");
}
fileUrl = URLDecoder.decode(fileUrl,"utf-8");
//根据链接解析文件信息
FileAttribute fileAttribute = fileHandlerService.getFileAttribute(fileUrl, req);
//下载文件
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileAttribute.getName());
//进行转换
this.coverAndWrite(rep,fileAttribute,response.getContent());
}
/**
* 通过文件将word转为pdf
* @param req
* @param rep
* @param file
*/
@PostMapping("/word2PdfByFile")
public void word2PdfByFile(HttpServletRequest req, HttpServletResponse rep,@RequestParam("file") MultipartFile file){
FileAttribute fileAttribute = new FileAttribute();
fileAttribute.setName(file.getOriginalFilename());
fileAttribute.setType(FileType.typeFromFileName(fileAttribute.getName()));
fileAttribute.setSuffix(KkFileUtils.suffixFromFileName(fileAttribute.getName()));
//上传文件至指定路径
File tempFile = upLoadFile(file);
String filePath = tempFile.getPath();
//进行转换
this.coverAndWrite(rep,fileAttribute,filePath);
}
/**
* 上传文件
* @param file
* @return
*/
private File upLoadFile(MultipartFile file){
File outFile = new File(fileDir + tempPath);
if (!outFile.exists() && !outFile.mkdirs()) {
throw new RuntimeException("创建文件夹【{}】失败,请检查目录权限!");
}
Path path = Paths.get(fileDir + tempPath + file.getOriginalFilename());
try (InputStream in = file.getInputStream(); OutputStream out = Files.newOutputStream(path)) {
StreamUtils.copy(in, out);
} catch (IOException e) {
throw new RuntimeException("文件上传失败"+e.getMessage());
}
return path.toFile();
}
}
2.3 接口测试
2.3.1 word文件准备
新建一个test.docx文件,如下图:
2.3.2 文件链接转pdf
- 生成word链接
- 执行转换
浏览器输入:http://127.0.0.1:8012/word2Pdf?fileUrl=http://127.0.0.1:8012/demo/test.docx,并将fileUrl替换为对应的链接,发起请求,成功后,会下载一个pdf文件,即为转换后的pdf,效果如下:
2.3.3 上传文件转pdf
使用Apifox进行接口调用,如下图进行请求:
执行成功后,会下载一个转换后的pdf,效果如下:
3 部署
可参考 【kkFileView二开之源码编译及部署】 文档中,【部署】目录下的方式,根据部署的平台选择合适的方式进行部署。
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。