小工具知识网

当前位置: 首页 > 行业知识 > spring boot 实现 PDF转换图片

行业知识

spring boot 实现 PDF转换图片

2026-12-02 23:12:17 来源:互联网转载

引入依赖

    org.springframework.boot    spring-boot-starter-parent    2.0.4.RELEASE                   org.springframework.boot        spring-boot-starter-web                    org.icepdf.os        icepdf-core        6.2.2    

前端页面

        PDf转���图片            .submitButton {            margin-top: 20px;            margin-left: 150px;            background-color: #e37e10;            border-radius: 10px;            border: 1px solid #ff8300;        }        

PDF转换图片工具


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; }

控制层接口

()
/** * @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工具类

/** * @description: PDF转换为图片的工具类 */@Componentpublic 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 fileList = new ArrayList();        for (int i = 0; i  0) {                        zos.write(buffer, 0, size);                    }                    zos.closeEntry();                    bis.close();                    file.delete();                } else {                    File[] files = file.listFiles();                    List childrenFileList = Arrays.asList(files);                    zipFile(childrenFileList, zos);                }            }        }    }}
()

上一篇:通过网站查询云服务器

下一篇:揭秘九宫格抽奖秘籍,轻松赢大奖的诀窍!