基于SpringBoot制作一个PDF切图小工具

 更新时间:2024年01月19日 10:42:27   作者:乐乐家的乐乐  
这篇文章主要为大家详细介绍了如何基于SpringBoot制作一个PDF切图小工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

老婆需要一个PDF工具,咱能说做不出来?

最近老婆需要将PDF文件分页切割并转成图片,但使用在线工具时经常遇到繁琐的广告。她问我能否做一个工具来简化这个过程。作为程序员,咱程序员能说不会做吗?当然不能,于是便有了我摸鱼写的一个小工具,【PDF切图】,将源码分享给大家。

【PDF切图】源码分享 跟着我一步一步来

1、首先我们需要一个SpringBoot项目

可以参考我的文章

【SpringBoot】从0~1 手把手教你搭建 分布式 项目

【SpringBoot】 一个优秀Maven项目的各Model间最佳继承设计

2、添加Maven依赖

在父Pom.xml文件中添加

        <pdfbox.version>2.0.9</pdfbox.version>    
​
            <dependency>
                <groupId>org.apache.pdfbox</groupId>
                <artifactId>pdfbox</artifactId>
                <version>${pdfbox.version}</version>
            </dependency>

pom.xml中添加

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
        </dependency>

3、封装我们的工具类(非常好用,直接分享给你们)

文件工具类FileUtils

package com.le.common.utils;
​
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
​
public class FileUtils {
​
​
    /**
     * 获取不带扩展名的文件名
     * @param fileName
     * @return
     */
    public static String getFileNameRemoveSuffix(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if (pos > 0) {
            return fileName.substring(0, pos);
        }
        return fileName;
    }
​
    /**
     * 递归删除指定目录及其内容。
     *
     * @param directory 要删除的目录
     */
    public static void deleteDirectory(File directory) {
        File[] allContents = directory.listFiles();
        if (allContents != null) {
            for (File file : allContents) {
                deleteDirectory(file);
            }
        }
        directory.delete();
    }
​
    /**
     * 将指定目录中的图像压缩为zip文件,并将其写入输出流中。
     *
     * @param directory     包含图像文件的目录
     * @param outputStream  要写入zip文件的输出流
     * @throws IOException 如果发生I/O错误
     */
    public static void zipImages(File directory, OutputStream outputStream) throws IOException {
        try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
            File[] imageFiles = directory.listFiles();
            if (imageFiles != null) {
                for (File imageFile : imageFiles) {
                    ZipEntry zipEntry = new ZipEntry(imageFile.getName());
                    zipOut.putNextEntry(zipEntry);
                    try (FileInputStream fis = new FileInputStream(imageFile)) {
                        byte[] bytes = new byte[1024];
                        int length;
                        while ((length = fis.read(bytes)) >= 0) {
                            zipOut.write(bytes, 0, length);
                        }
                    }
                }
            }
        }
    }
​
    /**
     * 创建临时文件
     * @return
     * @throws IOException
     */
    public static File createTempDirectory() throws IOException {
        File tempDir = File.createTempFile("temp", Long.toString(System.nanoTime()));
        if (!tempDir.delete() || !tempDir.mkdir()) {
            throw new IOException("Could not create temp directory: " + tempDir);
        }
        return tempDir;
    }
}

PDF工具类PdfUtils

package com.le.common.utils;
​
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
​
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
​
import org.apache.pdfbox.multipdf.Splitter;
​
public class PdfUtils {
​
    /**
     * 将PDF文件拆分为单独的图像,并将它们保存在指定的目录中。
     * PDF的每一页被转换为一个单独的图像文件。
     *
     * @param inputPdfFile       要拆分的输入PDF文件
     * @param outputImageDirectory 图像文件将要保存的目录
     * @throws IOException 如果发生I/O错误
     */
    public static void splitPdfToImages(File inputPdfFile, File outputImageDirectory) throws IOException {
        try (PDDocument document = PDDocument.load(inputPdfFile)) {
            Splitter splitter = new Splitter();
            List<PDDocument> pages = splitter.split(document);
            int pageIndex = 1;
            for (PDDocument page : pages) {
                PDFRenderer renderer = new PDFRenderer(page);
                BufferedImage image = renderer.renderImageWithDPI(0, 300, ImageType.RGB);
                // 写入图像文件
                File outputImage = new File(outputImageDirectory, "page" + pageIndex + ".png");
                ImageIO.write(image, "png", outputImage);
                pageIndex++;
                page.close();
            }
        }
    }
​
}

4、接口:PDF文件切割成图片输出

package com.le.admin.after.api.mytools;
​
import com.le.common.utils.FileUtils;
import com.le.common.utils.PdfUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
​
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
​
@RestController
@RequestMapping("/tools/pdf")
public class PdfToolController {
​
    /**
     * pdf文件切割成图片输出
     * @param pdfFile
     * @return
     */
    @PostMapping("/pdfCutToImage")
    public ResponseEntity<byte[]> processPdf(@RequestParam("pdfFile") MultipartFile pdfFile) {
        try {
            File tempDir = FileUtils.createTempDirectory();
            File pdfInputFile = new File(tempDir, pdfFile.getOriginalFilename());
            pdfFile.transferTo(pdfInputFile);
​
            // 将PDF文件拆分为单独的图像
            PdfUtils.splitPdfToImages(pdfInputFile, tempDir);
​
            // 将图像压缩为zip文件
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileUtils.zipImages(tempDir, baos);
​
            // 删除临时目录及其内容
            FileUtils.deleteDirectory(tempDir);
​
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=images.zip");
​
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.parseMediaType("application/zip"))
                    .body(baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
}

以上就是基于SpringBoot制作一个PDF切图小工具的详细内容,更多关于SpringBoot PDF切图的资料请关注脚本之家其它相关文章!

相关文章

  • Mybatis超级强大的动态SQL语句大全

    Mybatis超级强大的动态SQL语句大全

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,下面这篇文章主要给大家介绍了关于Mybatis超级强大的动态SQL语句的相关资料,需要的朋友可以参考下
    2022-05-05
  • springboot整合EHCache的实践方案

    springboot整合EHCache的实践方案

    EhCache是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。这篇文章给大家介绍了springboot整合EHCache的实践方案,需要的朋友参考下
    2018-01-01
  • SpringBoot统一返回处理出现cannot be cast to java.lang.String异常解决

    SpringBoot统一返回处理出现cannot be cast to java.lang.String异常解决

    这篇文章主要给大家介绍了关于SpringBoot统一返回处理出现cannot be cast to java.lang.String异常解决的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2023-09-09
  • Java中synchronized的几种使用方法

    Java中synchronized的几种使用方法

    本文主要介绍了Java中synchronized的几种使用方法,synchronized可用于修饰普通方法、静态方法和代码块,下面详细内容介绍,需要的小伙伴可以参考一下
    2022-05-05
  • Java简单计算两个日期月数差的方法

    Java简单计算两个日期月数差的方法

    这篇文章主要介绍了Java简单计算两个日期月数差的方法,结合实例形式分析了java使用Calendar类进行日期时间操作相关技巧,需要的朋友可以参考下
    2017-06-06
  • springboot整合nacos的入门Demo及Nacos安装部署

    springboot整合nacos的入门Demo及Nacos安装部署

    Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理,Nacos 致力于帮助您发现、配置和管理微服务,这篇文章主要介绍了springboot整合nacos的入门Demo,需要的朋友可以参考下
    2024-01-01
  • 解析HikariCP一百行代码轻松掌握多线程

    解析HikariCP一百行代码轻松掌握多线程

    这篇文章主要为大家介绍了HikariCP一百行代码解析,轻松掌握多线程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • 深入浅出了解happens-before原则

    深入浅出了解happens-before原则

    一提到happens-before原则,就让人有点“丈二和尚摸不着头脑”。这个涵盖了整个JMM中可见性原则的规则,究竟如何理解,把我个人一些理解记录下来。下面可以和小编一起学习
    2019-05-05
  • k8s部署java项目的实现

    k8s部署java项目的实现

    本文主要介绍了k8s部署java项目的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-12-12
  • Mybatis日期格式自动转换需要用到的两个注解说明

    Mybatis日期格式自动转换需要用到的两个注解说明

    这篇文章主要介绍了Mybatis日期格式自动转换需要用到的两个注解说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08

最新评论