由于在开发中需要适配不同的多端应用,在文件相关处理中也会存在相同的问题需要将文档转换为不同的格式展示,本节我们主要通过 一个小案例实现在 java环境下实现 PDF转换为JPG图片压缩包。
正文- 引入转换pdf的pom工具包
net.sf.cssbox pdf2dom1.7 org.apache.pdfbox pdfbox2.0.12 org.apache.pdfbox pdfbox-tools2.0.12
- 后端转换代码
@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前端代码
PDF转换为Jpg示例
退出
Test Staring
将文件拖到此处,或点击上传
只能上传PDF文件,且不超过50MB
.container {
padding: 10px;
.title {
font-size: 20px;
font-weight: bold;
}
}
- 验证结果
结语
ok,本节内容到这里就结束了,我们下期见。。。



