SpringBoot下实现PDF转word(Maven项目)

目录

前言

一、简易版本(只可以将PDF转为文字)

二、完整版本

1.引入库

2.编写工具类

3.编写controller类

4.vue前端实现下载

5.提示

三、注意事项

总结


前言

在日常工作学习中经常会遇到需要将PDF文件转成Word文件的场景,但是现在网上绝大部分PDF转Word的软件都是打着免费的噱头吸引你下载,但是使用时才发现,这些软件只能免费转几页,剩下的还是要购买会员。但是实际要转的PDF页数都远远超过了免费额度,这个时候,我们就可以通过这篇文章,自己写一个工具接口,来达到我们PDF转Word的目的

一、简易版本(只可以将PDF转为文字)

1、首先,进入Apache官网下载pdfbox最新版jar包,官网地址为:https://pdfbox.apache.org/download.cgi

2、将jar包导入到项目中,具体步骤如下:

(1)在项目resources目录下新建lib文件夹。并将下载的pdfbox最新版jar包放入lib文件夹

 

 

 

(2)进入project structure中导入项目中jar包

 

(3)在Modules目录下点击右方+添加jar包

 

(4)选择JARs and Directories

 

(5)选择jar包所在目录并点击ok

3、编写代码进行文件转换,代码如下:

public static void main(String[] args) {

    try {

        String pdfFile = "E:/乙方链账号.pdf";

        PDDocument doc = PDDocument.load(new File(pdfFile));

        int pagenumber = doc.getNumberOfPages();

        pdfFile = pdfFile.substring(0, pdfFile.lastIndexOf("."));

        String fileName = pdfFile + ".doc";

        File file = new File(fileName);

        if (!file.exists()){

            file.createNewFile();

        }

        FileOutputStream fos = new FileOutputStream(fileName);

        Writer writer = new OutputStreamWriter(fos, "UTF-8");

        PDFTextStripper stripper = new PDFTextStripper();

        stripper.setSortByPosition(true);// 排序

        stripper.setStartPage(1);// 设置转换的开始页

        stripper.setEndPage(pagenumber);// 设置转换的结束页

        stripper.writeText(doc, writer);

        writer.close();

        doc.close();

        System.out.println("pdf转换word成功!");

    } catch (IOException e) {

        e.printStackTrace();

    }

}

 

 

二、完整版本

1.引入库

完整版不仅可以转换文字,还可以转换图片,并将样式都转换好,因此需要第三方工具包

我这边使用的是Spire的PDFmaven库

首先,需要使用Spire的maven私服,在pom文件中添加以下代码:

<repositories>
   <repository>
     <id>com.e-iceblue</id>
     <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
   </repository>
</repositories>

然后导入PDF相关工具包

<dependency>
    <groupId> e-iceblue </groupId>
    <artifactId>spire.pdf</artifactId>
    <version>3.4.2</version>
</dependency>

2.编写工具类

该工具类主要作用是将前端传过来的MultipartFile转成File类型,具体代码如下

public class CommonUtil {

    /**
     * MultipartFile 转换成File
     *
     * @param multfile 原文件类型
     * @return File
     */
    public static File multipartToFile(MultipartFile multfile) throws IOException {
        File file = null;
//        file = File.createTempFile("prefix","_" + multfile.getOriginalFilename());
        String projectPath = System.getProperty("user.dir");
        file = new File(projectPath + "/prefix_" + multfile.getOriginalFilename());

        multfile.transferTo(file);
        return file;
    }


}

3.编写controller类

实现接收PDF文件,转成Word文件并将转好的文件返回以供前端下载。具体代码如下:

    @PostMapping("pdfToDoc")
    public void pdfToDoc(@RequestParam("pdfFile") MultipartFile pdfFile, HttpServletResponse response) throws Exception {

        // 将MultiparFile转为File
        File file = CommonUtil.multipartToFile(pdfFile);

        // 创建Pdf工具类对象
        PdfDocument pdf = new PdfDocument();

        // 拼接Word文件名
        String projectPath = System.getProperty("user.dir");
        String name = file.getName();
        pdf.loadFromFile(projectPath + "/" + name);

        //保存为Word格式
        String fileName = file.getName().substring(0, file.getName().lastIndexOf(".")) + ".docx";
        pdf.saveToFile(fileName, FileFormat.DOCX);

        // 将问文件转为字节流返回供前端下载
        File wordFile = new File(fileName);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");

        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(wordFile);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            log.info("word文件成功下载");

        } catch (Exception e) {
            log.info("word文件下载失败");
        } finally {
            if (bis != null) {
                try {
                    // 结束后关闭文件流
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    // 结束后关闭文件流
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 最后删除转换过程中生成的文件
            wordFile.delete();
            file.delete();
        }
    }

4.vue前端实现下载

个人原因,前端选择了vue,在使用axios请求时想要把接口返回的json转换成文件并下载需要额外处理,具体代码如下:

handleAvatarSuccess(file) {
      // 将上传的文件放入FormData对象中作为请求参数传递给后端
      var data = new FormData()
      data.append('pdfFile', file)
      console.log(file.name)
      this.fileName = file.name
      // 发送Post请求
      AdminApi.pdfToDoc(data).then(response => {
        console.log(response)
        // 将请求返回的数据封装成文件并下载
        this.downloadFile(response.data)
      })
    },
    downloadFile(data) {
      // 文件导出
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', this.fileName.substring(0, this.fileName.lastIndexOf('.')) + '.docx')

      document.body.appendChild(link)
      link.click()
    }

5.提示

因为axios请求默认返回数据类型为json,无法直接下载,因此需要修改返回数据类型为blob,修改方法如下:

在axios设置中将responseType设置为 ‘blob’即可

三、注意事项

Spring框架默认上传最大文件为10M,如果要转换的PDF文件超过这个大小,则接口会报错,这时候需要修改最大上传文件大小具体代码为:

@Configuration
public class HttpConfiguration {

    /**
     * 文件上传配置
     *
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //  单个数据大小
        factory.setMaxFileSize(DataSize.ofMegabytes(50)); // KB,MB
        /// 总上传数据大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(200));
        return factory.createMultipartConfig();
    }
}

总结

如果只是将大部分内容为文字的pdf转为Word文件那使用第一种方式即可,简单而且效率高;

但是如果PDF内容比较复杂则需要第二种方法,第一种方法已经不再适用了,但是第二种方法效率较第一种稍微低一点,请根据情况选择;

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值