关于java:Java实现PDF文件转换为图片

40次阅读

共计 5146 个字符,预计需要花费 13 分钟才能阅读完成。

引入依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <!--SpringMVC 的依赖,不便咱们能够获取前端传递过去的文件信息 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--icepdf,用来将 pdf 文件转换为图片的依赖 -->
    <dependency>
        <groupId>org.icepdf.os</groupId>
        <artifactId>icepdf-core</artifactId>
        <version>6.2.2</version>
    </dependency>
</dependencies>

前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PDf 转换图片 </title>
    <style>
        .submitButton {
            margin-top: 20px;
            margin-left: 150px;
            background-color: #e37e10;
            border-radius: 10px;
            border: 1px solid #ff8300;
        }
    </style>
</head>
<body>
<div style="text-align: center">
    <h1>PDF 转换图片工具 </h1>
    <form action="/pdf/to/image" enctype="multipart/form-data" method="post" onsubmit="return allowFileType()">
        <input type="file" id="file" name="file" placeholder="请抉择 PDF 文件" onchange="allowFileType()" style="border: 1px solid black;"><br>
        <input type="submit" value="一键转换图片" class="submitButton">
    </form>
</div>
</body>
<script>
    function allowFileType() {let file = document.getElementById("file").files[0];
        let fileName = file.name;
        let suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length).toLowerCase();
        if('.pdf' != suffix) {alert("只容许传入 PDF 格局的文件!");
            return false;
        }
        return true;
    }
</script>
</html>

管制层接口

外汇 MT4 教程 https://www.kaifx.cn/mt4.html

package com.hrp.controller;

import com.hrp.util.ImageUtils;
import org.springframework.stereotype.Controller;
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.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * @description: 用于解决 Pdf 相干的申请
 */
@Controller
@RequestMapping("pdf")
public class PdfController {@PostMapping("to/image")
    public void pdfToImage(@RequestParam("file") MultipartFile file,HttpServletResponse response) throws Exception{ImageUtils.pdfToImage(file,response);
    }

}

Image 工具类

package com.hrp.util;

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @description: PDF 转换为图片的工具类
 */
@Component
public class ImageUtils {

    /**
     * 图片文件格式
     */
    public static final String FORMAT_NAME = "png";
    /**
     * 图片文件后缀名
     */
    public static final String PNG_SUFFIX = ".png";
    /**
     * 压缩文件后缀名
     */
    public static final String ZIP_SUFFIX = ".zip";

    /**
     * 对外的凋谢接口,用于将 PDF 文件转换为图片文件压缩包进行下载
     *
     * @param file SpringMVC 获取的图片文件
     * @param response
     * @throws Exception
     */
    public static void pdfToImage(MultipartFile file, HttpServletResponse response) throws Exception {File zipFile = generateImageFile(file);
        downloadZipFile(zipFile, response);
    }


    /**
     * 将 PDF 文件转换为多张图片并放入一个压缩包中
     *
     * @param file SpringMVC 获取的图片文件
     * @return 图片文件压缩包
     * @throws Exception 抛出异样
     */
    private static File generateImageFile(MultipartFile file) throws Exception {String fileName = file.getOriginalFilename();
        Document document = new Document();
        document.setByteArray(file.getBytes(), 0, file.getBytes().length, fileName);

        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < document.getNumberOfPages(); i++) {BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN,
                    Page.BOUNDARY_CROPBOX, 0F, 2.5F);
            File imageFile = new File((i + 1) + PNG_SUFFIX);
            ImageIO.write(image, FORMAT_NAME, imageFile);
            image.flush();
            fileList.add(imageFile);
        }
        document.dispose();

        String directoryName = fileName.substring(0, fileName.lastIndexOf("."));
        File zipFile = new File(directoryName + ZIP_SUFFIX);
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
        zipFile(fileList, zos);
        zos.close();
        return zipFile;
    }

    /**
     * 下载 zip 文件
     *
     * @param zipFile  zip 压缩文件
     * @param response HttpServletResponse
     * @throws IOException IO 异样
     */
    private static void downloadZipFile(File zipFile, HttpServletResponse response) throws IOException {FileInputStream fis = new FileInputStream(zipFile);
        byte[] bytes = new byte[fis.available()];
        fis.read(bytes);
        fis.close();

        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));
        OutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
        out.close();
        zipFile.delete();}

    /**
     * 压缩文件
     *
     * @param inputFiles 具体须要压缩的文件汇合
     * @param zos        ZipOutputStream 对象
     * @throws IOException IO 异样
     */
    private static void zipFile(List<File> inputFiles, ZipOutputStream zos) throws IOException {byte[] buffer = new byte[1024];
        for (File file : inputFiles) {if (file.exists()) {if (file.isFile()) {BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                    zos.putNextEntry(new ZipEntry(file.getName()));
                    int size = 0;
                    while ((size = bis.read(buffer)) > 0) {zos.write(buffer, 0, size);
                    }
                    zos.closeEntry();
                    bis.close();
                    file.delete();} else {File[] files = file.listFiles();
                    List<File> childrenFileList = Arrays.asList(files);
                    zipFile(childrenFileList, zos);
                }
            }
        }
    }

}

正文完
 0