前军教程网

中小站长与DIV+CSS网页布局开发技术人员的首选CSS学习平台

如何在Spring Boot中实现将上传的PDF文件按页面拆分成单个文件?

文件上传操作,作为Web应用程序开发过程中的一个常见的需求,但是如何将上传到服务器的PDF文件按照页码拆分成多个单页的PDF实现单页面读取操作却是一个比较麻烦的操作,下面我们就来详细介绍一下如何在Spring Boot中实现这个需求。

依赖配置

首先想要在Java中实现对于PDF文件的操作,那么我们可以通过Apache PDFBox组件来实现,所以我们需要在POM文件中引入Apache PDFBox的相关的配置依赖,如下所示。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.27</version>
    </dependency>
</dependencies>

文件上传

既然要实现文件的上传操作,我们可以通过模板引擎技术创建一个用来进行文件上传操作的页面如下所示。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>PDF拆分</title>
</head>
<body>
    <h1>上传 PDF 文件</h1>
    <form method="post" enctype="multipart/form-data" th:action="@{/upload}">
        <input type="file" name="file" accept="application/pdf"/>
        <button type="submit">上传并拆分</button>
    </form>
</body>
</html>

页面创建完成之后,接下来我们就需要创建Controller的方法用来接收文件上传操作。

@Controller
public class PDFController {

    @Autowired
    private PDFService pdfService;

    @RequestMapping("/")
    public String index() {
        return "upload";
    }

    @PostMapping("/upload")
    public String uploadPDF(@RequestParam("file") MultipartFile file, Model model) {
        try {
            pdfService.splitPDF(file);
            model.addAttribute("message", "PDF 文件拆分成功!");
        } catch (IOException e) {
            e.printStackTrace();
            model.addAttribute("message", "文件处理失败:" + e.getMessage());
        }
        return "upload";
    }
}

服务层实现

上传文件完成之后,接下来就需要将PDF拆分成一页页的PDF文件,如下所示。

@Service
public class PDFService {

    public void splitPDF(MultipartFile file) throws IOException {
        // 将上传的文件转换为 PDFBox 支持的对象
        try (PDDocument document = PDDocument.load(file.getInputStream())) {
            int pageCount = document.getNumberOfPages();

            // 创建输出目录
            File outputDir = new File("output");
            if (!outputDir.exists()) {
                outputDir.mkdir();
            }

            // 按页拆分 PDF
            for (int i = 0; i < pageCount; i++) {
                PDPage page = document.getPage(i);
                try (PDDocument singlePageDocument = new PDDocument()) {
                    singlePageDocument.addPage(page);
                    File outputFile = new File(outputDir, "page-" + (i + 1) + ".pdf");
                    singlePageDocument.save(outputFile);
                }
            }
        }
    }
}

接下来就是启动项目,访问页面将文件通过页面上传到文件后端进行文件拆分处理,上传的 PDF文件将被拆分成多个单页 PDF 文件,并以page-1.pdf, page-2.pdf等文件名保存。

总结

通过上面的实现我们就可以将PDF拆分成单页的文件,然后就可以在前端展示的时候,通过Css样式实现类似于翻书效果的阅读方式增加用户体验的同时,也可以保证在高并发场景下文件读取的效率。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言