(二)java项目中的文档转换案例实战——PDF转换为JPG图片压缩包
作者:互联网
前言
由于在开发中需要适配不同的多端应用,在文件相关处理中也会存在相同的问题需要将文档转换为不同的格式展示,本节我们主要通过 一个小案例实现在 java环境下实现 PDF转换为JPG图片压缩包。
正文
- 引入转换pdf的pom工具包
<!--pdf转化为html或者图片--> <dependency> <groupId>net.sf.cssbox</groupId> <artifactId>pdf2dom</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.12</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox-tools</artifactId> <version>2.0.12</version> </dependency>
- 后端转换代码
@ApiOperation(value = "pdf转换为jpg") @PostMapping(value = "pdfToJpg") public void pdfToJpg(HttpServletResponse response, @RequestPart("file") MultipartFile file) { try { PDDocument doc = PDDocument.load(file.getInputStream()); //遍历处理pdf附件 int size = doc.getNumberOfPages(); PDFRenderer reader = new PDFRenderer(doc); //文件临时存储目录 String location = System.getProperty("user.dir") + "/" + dirTmp; for (int i = 0; i < size; i++) { BufferedImage bufferedImage = reader.renderImage(i, 3f); //生成图片,保存位置 if (!FileUtil.exist(location + "/out/")) { File fileOut = new File(location + "/out/"); if (!fileOut.exists()) { fileOut.mkdirs(); } } FileOutputStream out = new FileOutputStream(location + "/out/" + i + ".jpg"); ImageIO.write(bufferedImage, "jpg", out); out.close(); } String destination = location + "/in/" + UUID.randomUUID() + ".zip"; String source = location + "/out"; ZipUtil.zip(source, destination); //需要编码否则中文乱码 response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(IdWorker.getIdStr() + ".zip", "UTF-8")); response.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); response.setContentType("application/zip;charset=utf-8"); response.setCharacterEncoding("UTF-8"); //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(destination)); byte[] buff = new byte[bis.available()]; bis.read(buff); bis.close(); OutputStream out = response.getOutputStream(); //输出数据文件 out.write(buff); //释放缓存 out.flush(); //关闭输出流 out.close(); FileUtil.del(source); FileUtil.del(destination); } catch (IOException ioException) { ioException.printStackTrace(); } }
- vue前端代码
<template> <div class="container"> <div class="title"> <span>PDF转换为Jpg示例</span> <el-divider direction="vertical"></el-divider> <router-link to="home"> <span style="font-size: 18px;">退出</span> </router-link> </div> <el-divider>Test Staring</el-divider> <div style="text-align: center;"> <el-upload ref="upload" class="upload-demo" drag :http-request="myUploadFile"> <i class="el-icon-upload"></i> <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div> <div class="el-upload__tip" slot="tip">只能上传PDF文件,且不超过50MB</div> </el-upload> </div> </div> </template> <script> export default { name: "PdfToJpg", data() { return {} }, methods: { //文件上传成功的回调 myUploadFile(data) { const formData = new FormData(); formData.append("file", data.file); this.$http.post('/fileTransfer/pdfToJpg', formData, { responseType: 'blob', headers: { 'Content-Type': 'multipart/form-data', }, }).then(res => { const blob = new Blob([res.data], {type: 'application/zip'}); let timestamp = (new Date()).valueOf(); const fileName = timestamp + '.zip' if ('download' in document.createElement('a')) { // 非IE下载 const elink = document.createElement('a') elink.download = fileName elink.style.display = 'none' elink.href = window.URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() window.URL.revokeObjectURL(elink.href) // 释放URL 对象 document.body.removeChild(elink) } else { // IE10+下载 navigator.msSaveBlob(blob, fileName) } }).catch(error => { this.$message.error(error); }); } } } </script> <style scoped lang="scss"> .container { padding: 10px; .title { font-size: 20px; font-weight: bold; } } </style>
- 验证结果
结语
ok,本节内容到这里就结束了,我们下期见。。。
标签:elink,zip,JPG,location,new,PDF,out,response,转换 来源: https://blog.csdn.net/yprufeng/article/details/122087728