前言
由于在开发中需要适配不同的多端应用,在文件相关处理中也会存在相同的问题需要将文档转换为不同的格式展示,本节我们主要通过 一个小案例实现在 java环境下实现 PDF格式转换为网页HTML格式。
正文
- 引入转换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>
- 后端转换代码
package com.yundi.atp.platform.module.test.controller; import cn.hutool.core.codec.Base64; import cn.hutool.core.io.FileUtil; import com.baomidou.mybatisplus.core.toolkit.IdWorker; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.io.IOUtils; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; 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.nio.charset.StandardCharsets; /** * @Author: beiming * @Description: * @Date: 2021/12/17 18:29 * @Version: 1.0.0 */ @Api(tags = {"文件转换"}) @RestController @RequestMapping(value = "/fileTransfer") public class FileTransferController { @Value(value = "${atp.dir}") private String dirTmp; @ApiOperation(value = "pdf转换为html") @PostMapping(value = "pdfToHtml") public void pdfToHtml(HttpServletResponse response, MultipartFile file) { try { StringBuffer buffer = new StringBuffer(); PDDocument doc = PDDocument.load(file.getInputStream()); //遍历处理pdf附件 buffer.append("<!doctype html>\r\n"); buffer.append("<head>\r\n"); buffer.append("<meta charset=\"UTF-8\">\r\n"); buffer.append("</head>\r\n"); buffer.append("<body>\r\n"); buffer.append("<style>\r\n"); buffer.append("img {background-color:#fff; text-align:center; width:100%; max-width:100%;}\r\n"); buffer.append("</style>\r\n"); int size = doc.getNumberOfPages(); PDFRenderer reader = new PDFRenderer(doc); for (int i = 0; i < size; i++) { BufferedImage bufferedImage = reader.renderImage(i, 3f); //文件临时存储目录 String location = System.getProperty("user.dir") + "/" + dirTmp; //生成图片,保存位置 FileOutputStream out = new FileOutputStream(location + "/" + i + ".jpg"); ImageIO.write(bufferedImage, "jpg", out); String encode = Base64.encode(new File(location + "/" + i + ".jpg")); //将图片路径追加到网页文件里 buffer.append("<img src=\"data:image/jpg;base64," + encode + "\"/>\r\n"); out.close(); FileUtil.del(location + "/" + i + ".jpg"); } doc.close(); buffer.append("</body>\r\n"); buffer.append("</html>"); InputStream inputStream = IOUtils.toInputStream(buffer.toString(), StandardCharsets.UTF_8); response.reset(); response.setContentType(""); response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(IdWorker.getIdStr(), "UTF-8")); byte[] buf = new byte[1024]; int len; OutputStream outputStream = response.getOutputStream(); while ((len = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, len); } inputStream.close(); outputStream.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } }
- 前端代码
<template> <div class="container"> <div class="title"> <span>PDF转换为HTML示例</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 :on-success="handlerOnSuccess" action="/fileTransfer/pdfToHtml"> <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: "PdfToHtml", data() { return {} }, methods: { //文件上传成功的回调 handlerOnSuccess(data) { const url = window.URL.createObjectURL(new Blob([data], {type: 'text/html'})); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'test.html') // 下载文件的名称及文件类型后缀 document.body.appendChild(link) link.click(); document.body.removeChild(link); // 下载完成移除元素 window.URL.revokeObjectURL(url); // 释放掉blob对象 } } } </script> <style scoped lang="scss"> .container { padding: 10px; .title { font-size: 20px; font-weight: bold; } } </style>
- 验证结果
结语
ok,关于PDF转换为网页HTML的案例实战到这里就结束了,我们下期见。。。