ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

(二)java项目中的文档转换案例实战——PDF转换为JPG图片压缩包

2021-12-27 19:00:02  阅读:162  来源: 互联网

标签:elink zip JPG location new PDF out response 转换


前言

由于在开发中需要适配不同的多端应用,在文件相关处理中也会存在相同的问题需要将文档转换为不同的格式展示,本节我们主要通过 一个小案例实现在 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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有