kkFileView二开之word转pdf接口

kkFileView二开系列文章:

  1. kkFileView二开之源码编译及部署
  2. kkFileView二开之内外网转换
  3. kkFileView二开之word转pdf接口
  4. kkFileView二开之Excel转pdf接口
  5. kkFileView二开之pdf转图片接口
  6. kkFileView二开之企业级安全问题处理
    对应二开代码仓库:https://gitee.com/wbj_1/kk-file-view

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

  1. 生成word链接
    在这里插入图片描述
  2. 执行转换
    浏览器输入: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二开之源码编译及部署】 文档中,【部署】目录下的方式,根据部署的平台选择合适的方式进行部署。

### PyCharm 打开文件显示全的解决方案 当遇到PyCharm打开文件显示全的情况时,可以尝试以下几种方法来解决问题。 #### 方法一:清理缓存并重启IDE 有时IDE内部缓存可能导致文件加载异常。通过清除缓存再启动程序能够有效改善此状况。具体操作路径为`File -> Invalidate Caches / Restart...`,之后按照提示完成相应动作即可[^1]。 #### 方法二:调整编辑器字体设置 如果是因为字体原因造成的内容显示问题,则可以通过修改编辑区内的文字样式来进行修复。进入`Settings/Preferences | Editor | Font`选项卡内更改合适的字号大小以及启用抗锯齿功能等参数配置[^2]。 #### 方法三:检查项目结构配置 对于某些特定场景下的源码视图缺失现象,可能是由于当前工作空间未能正确识别全部模块所引起。此时应该核查Project Structure的Content Roots设定项是否涵盖了整个工程根目录;必要时可手动添加遗漏部分,并保存变更生效[^3]。 ```python # 示例代码用于展示如何获取当前项目的根路径,在实际应用中可根据需求调用该函数辅助排查问题 import os def get_project_root(): current_file = os.path.abspath(__file__) project_dir = os.path.dirname(current_file) while not os.path.exists(os.path.join(project_dir, '.idea')): parent_dir = os.path.dirname(project_dir) if parent_dir == project_dir: break project_dir = parent_dir return project_dir print(f"Current Project Root Directory is {get_project_root()}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值