当前位置: 首页 > news >正文

spring boot 实现 PDF转换图片

引入依赖

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.4.RELEASE</version><relativePath/>
</parent><dependencies>   <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--将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>

控制层接口

/*** @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转换为图片的工具类*/
@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);}}}}}

相关文章:

  • 鸿蒙Harmony应用开发—ArkTS声明式开发(基础手势:XComponent)
  • maven一点通
  • pdf文件属性的删除
  • 一款基于 SpringCloud 开发的AI聊天机器人系统,已对接GPT-4.0,非常强大
  • 还原wps纯粹的编辑功能
  • Apache Doris 如何基于自增列满足高效字典编码等典型场景需求
  • tp8 mpdf 导出pdf
  • C语言经典算法-9
  • RabbitMQ介绍及搭建
  • 【Vue3】自定义Input组件
  • 后端工程师快速使用vue和Element
  • 2024年敏捷产品负责人CSPO认证培训
  • Solidity 智能合约开发 - 基础:基础语法 基础数据类型、以及用法和示例
  • 如何使用IDE端通义灵码
  • C语言 扫雷游戏
  • [微信小程序] 使用ES6特性Class后出现编译异常
  • 【comparator, comparable】小总结
  • android百种动画侧滑库、步骤视图、TextView效果、社交、搜房、K线图等源码
  • Cookie 在前端中的实践
  • JAVA_NIO系列——Channel和Buffer详解
  • linux学习笔记
  • mysql中InnoDB引擎中页的概念
  • PHP的类修饰符与访问修饰符
  • Swoft 源码剖析 - 代码自动更新机制
  • win10下安装mysql5.7
  • 百度地图API标注+时间轴组件
  • 道格拉斯-普克 抽稀算法 附javascript实现
  • 前嗅ForeSpider教程:创建模板
  • 浅析微信支付:申请退款、退款回调接口、查询退款
  • 通过获取异步加载JS文件进度实现一个canvas环形loading图
  • 应用生命周期终极 DevOps 工具包
  • 原生Ajax
  • SAP CRM里Lead通过工作流自动创建Opportunity的原理讲解 ...
  • 浅谈sql中的in与not in,exists与not exists的区别
  • #LLM入门|Prompt#1.8_聊天机器人_Chatbot
  • (14)目标检测_SSD训练代码基于pytorch搭建代码
  • (Arcgis)Python编程批量将HDF5文件转换为TIFF格式并应用地理转换和投影信息
  • (Java实习生)每日10道面试题打卡——JavaWeb篇
  • (rabbitmq的高级特性)消息可靠性
  • (附源码)ssm高校实验室 毕业设计 800008
  • (一)80c52学习之旅-起始篇
  • *** 2003
  • .java 9 找不到符号_java找不到符号
  • .net core 源码_ASP.NET Core之Identity源码学习
  • .net on S60 ---- Net60 1.1发布 支持VS2008以及新的特性
  • .NET/ASP.NETMVC 大型站点架构设计—迁移Model元数据设置项(自定义元数据提供程序)...
  • .net6 webapi log4net完整配置使用流程
  • .Net环境下的缓存技术介绍
  • ::什么意思
  • @Autowired和@Resource装配
  • @modelattribute注解用postman测试怎么传参_接口测试之问题挖掘
  • [\u4e00-\u9fa5] //匹配中文字符
  • [22]. 括号生成
  • [Angular 基础] - 指令(directives)
  • [BSGS算法]纯水斐波那契数列