【Java】SpringBoot后端格式转换:把Word转成PDF再按页转成图片在前端展示(Linux)
ConvertUtil
- 1. word2pdf
- 1.1 aspose-word插件
- 1.2 word转pdf
- 1.2.1 添加license文件
- 1.2.2 具体实现
- 2. pdf2imgByPage
- 2.1 icepdf插件
- 2.1.1 安装插件
- 2.1.2 ImageIO missing required plug-in to read JPEG 2000 images
- 2.2 pdf按页转换成图片
- 2.2.1 方法
- 2.2.2 与Controller层的交互
- 3. 完整代码实现
- 3.1 ConvertUtil
- 2.2 FileController
需求如标题。
1. word2pdf
1.1 aspose-word插件
首先要解决在linux下将word转换成pdf,使用aspose-words。
插件地址:java实现Word转Pdf(Windows、Linux通用)
附在maven项目中导入已有jar包的方法:
在idea中执行mvn命令:IDEA执行maven命令
安装命令:
模板:
mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>
mvn install:install-file -DgroupId=com.aspose -DartifactId=aspose-words -Dversion=15.8.0 -Dpackaging=jar -Dfile=aspose-words-15.8.0-jdk16.jar
.xml中添加依赖
<dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>15.8.0</version>
</dependency>
1.2 word转pdf
1.2.1 添加license文件
license.xml在resources根目录下,防止转换出来的pdf有水印
<?xml version="1.0" encoding="UTF-8" ?>
<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
1.2.2 具体实现
public static boolean getLicense() {boolean result = false;InputStream is = null;try {Resource resource = new ClassPathResource("license.xml");is = resource.getInputStream();//InputStream is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}return result;}public static boolean doc2pdf(String inPath, String outPath) {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return false;}FileOutputStream os = null;try {long old = System.currentTimeMillis();File file = new File(outPath); // 新建一个空白pdf文档os = new FileOutputStream(file);com.aspose.words.Document doc = new com.aspose.words.Document(inPath); // Address是将要被转化的word文档doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,// EPUB, XPS, SWF 相互转换long now = System.currentTimeMillis();System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时} catch (Exception e) {e.printStackTrace();return false;}finally {if (os != null) {try {os.flush();os.close();} catch (IOException e) {e.printStackTrace();}}}return true;}
2. pdf2imgByPage
2.1 icepdf插件
2.1.1 安装插件
pom.xml中添加依赖:
<dependency><groupId>org.icepdf.os</groupId><artifactId>icepdf-core</artifactId><version>6.1.2</version><exclusions><exclusion><groupId>javax.media</groupId><artifactId>jai-core</artifactId></exclusion></exclusions></dependency>
2.1.2 ImageIO missing required plug-in to read JPEG 2000 images
添加依赖:
<dependency><groupId>com.github.jai-imageio</groupId><artifactId>jai-imageio-core</artifactId><version>1.3.1</version></dependency><dependency><groupId>com.github.jai-imageio</groupId><artifactId>jai-imageio-jpeg2000</artifactId><version>1.3.0</version></dependency>
2.2 pdf按页转换成图片
2.2.1 方法
public static BufferedImage pdf2ImgByPage(String pdfPath, float zoom, int page) throws PDFSecurityException, PDFException, IOException {org.icepdf.core.pobjects.Document document = null;float rotation = 0f;document = new org.icepdf.core.pobjects.Document();document.setFile(pdfPath);BufferedImage img = (BufferedImage) document.getPageImage(page,GraphicsRenderingHints.SCREEN,Page.BOUNDARY_CROPBOX,rotation,zoom);document.dispose();return img;}
2.2.2 与Controller层的交互
@RequestMapping("/previewFile")public void previewFileByPage(HttpServletRequest request, HttpServletResponse response) throws IOException, PDFSecurityException, PDFException {int id = Integer.parseInt(request.getParameter("id"));int page = Integer.parseInt(request.getParameter("page"));File file = fileService.getFileByID(id);BufferedImage img = ConvertUtil.pdf2ImgByPage(file.getPath(), 1, page);ByteArrayOutputStream os = new ByteArrayOutputStream();ImageIO.write(img, "png", os);InputStream in = new ByteArrayInputStream(os.toByteArray());ServletOutputStream sos = null;try {sos = response.getOutputStream();byte[] b = new byte[1024];while (in.read(b) != -1) {sos.write(b); //输出}sos.flush(); //刷新} catch (Exception e) {e.printStackTrace();} finally {try {in.close(); //关闭文件读取流,输出流sos.close();} catch (IOException e) {e.printStackTrace();}}}
3. 完整代码实现
3.1 ConvertUtil
package com.main.datainfo.utils;import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.DecimalFormat;
import java.util.Iterator;public class ConvertUtil {public static final String FILETYPE_JPG = "jpg";public static boolean getLicense() {boolean result = false;InputStream is = null;try {Resource resource = new ClassPathResource("license.xml");is = resource.getInputStream();//InputStream is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}return result;}public static boolean doc2pdf(String inPath, String outPath) {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return false;}FileOutputStream os = null;try {long old = System.currentTimeMillis();File file = new File(outPath); // 新建一个空白pdf文档os = new FileOutputStream(file);com.aspose.words.Document doc = new com.aspose.words.Document(inPath); // Address是将要被转化的word文档doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,// EPUB, XPS, SWF 相互转换long now = System.currentTimeMillis();System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时} catch (Exception e) {e.printStackTrace();return false;}finally {if (os != null) {try {os.flush();os.close();} catch (IOException e) {e.printStackTrace();}}}return true;}/**** 将指定的pdf文件转换为指定路径的图片** @param pdfPath 原文件路径,例如d:/test/test.pdf** @param imgPath 图片生成路径,例如 d:/test/** @param zoom 缩略图显示倍数,1表示不缩放,0.3则缩小到30%**/public static void pdf2Img(String pdfPath, String imgPath, float zoom) throws PDFException, PDFSecurityException, IOException {org.icepdf.core.pobjects.Document document = null;float rotation = 0f;document = new org.icepdf.core.pobjects.Document();document.setFile(pdfPath);int maxPages = document.getPageTree().getNumberOfPages();for (int i = 0; i < maxPages; i++) {BufferedImage img = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, zoom);Iterator iter = ImageIO.getImageWritersBySuffix(FILETYPE_JPG);ImageWriter writer = (ImageWriter) iter.next();File outFile = new File(imgPath + new File(pdfPath).getName() + "_" + new DecimalFormat("000").format(i) + "." + FILETYPE_JPG);FileOutputStream out = new FileOutputStream(outFile);ImageOutputStream outImage = ImageIO.createImageOutputStream(out);writer.setOutput(outImage);writer.write(new IIOImage(img, null, null));}System.out.println("转换完成");}public static int getPageSize(String pdfPath) throws PDFSecurityException, PDFException, IOException {org.icepdf.core.pobjects.Document document = null;document = new org.icepdf.core.pobjects.Document();document.setFile(pdfPath);return document.getPageTree().getNumberOfPages();}public static BufferedImage pdf2ImgByPage(String pdfPath, float zoom, int page) throws PDFSecurityException, PDFException, IOException {org.icepdf.core.pobjects.Document document = null;float rotation = 0f;document = new org.icepdf.core.pobjects.Document();document.setFile(pdfPath);BufferedImage img = (BufferedImage) document.getPageImage(page,GraphicsRenderingHints.SCREEN,Page.BOUNDARY_CROPBOX,rotation,zoom);document.dispose();return img;}
}
2.2 FileController
package com.main.datainfo.controller;import com.main.datainfo.entity.File;
import com.main.datainfo.service.FileService;
import com.main.datainfo.utils.ConvertUtil;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;@RestController
@RequestMapping("/file")
public class FileController {@Autowiredprivate FileService fileService;@RequestMapping("/previewFile")public void previewFileByPage(HttpServletRequest request, HttpServletResponse response) throws IOException, PDFSecurityException, PDFException {int id = Integer.parseInt(request.getParameter("id"));int page = Integer.parseInt(request.getParameter("page"));File file = fileService.getFileByID(id);BufferedImage img = ConvertUtil.pdf2ImgByPage(file.getPath(), 1, page);ByteArrayOutputStream os = new ByteArrayOutputStream();ImageIO.write(img, "png", os);InputStream in = new ByteArrayInputStream(os.toByteArray());ServletOutputStream sos = null;try {sos = response.getOutputStream();byte[] b = new byte[1024];while (in.read(b) != -1) {sos.write(b); //输出}sos.flush(); //刷新} catch (Exception e) {e.printStackTrace();} finally {try {in.close(); //关闭文件读取流,输出流sos.close();} catch (IOException e) {e.printStackTrace();}}}}
【Java】SpringBoot后端格式转换:把Word转成PDF再按页转成图片在前端展示(Linux)相关推荐
- 基于java的格式转换,word 转 pdf、word 转图片、office 格式转换、在线文件预览
一.项目简介 不管你是java程序员.c++程序员,python程序员,在开发项目中肯定遇到过格式转换的问题,如何轻松搞定格式转换的问题呢?当然是百度啦!面向百度编程已经成为当下程序员的日常操作. 基 ...
- documents4j:Java文档格式转换开发库
为什么80%的码农都做不了架构师?>>> http://hao.jobbole.com/documents4j/ documents4j:Java文档格式转换开发库 docum ...
- word转换成pdf,包括导航目录和图片不变黑
1.word转换成pdf,包括导航目录和图片不变黑: 有些时候将word转换成pdf,我们会发现生成的文件要么不带导航目录,要么就是图片显示有问题,比如变黑.变黑是因为某些图片在作图时修改了透明度,因 ...
- java+icepdf+下载_Java使用icepdf将pdf文件按页转成图片
本文实例为大家分享了Java使用icepdf将pdf文件按页转成图片的具体代码,供大家参考,具体内容如下 Maven icepdf包,这里过滤掉jai-core org.icepdf.os icepd ...
- xhtmlrenderer 将html转换成pdf,完美css,带图片,手动分页,解决内容断开的问题
xhtmlrenderer 将html转换成pdf,完美css,带图片,手动分页,解决内容断开的问题 参考文章: (1)xhtmlrenderer 将html转换成pdf,完美css,带图片,手动分页 ...
- SpringBoot日期格式转换,SpringBoot配置全局日期格式转换器
文章目录 1. SpringBoot设置后台向前台传递Date日期格式 1.1 方式1:配置文件修改 1.2 方式2:在javabean实体类上加注解 I. `@JsonFormat`注解 II. ` ...
- Java时间日期格式转换
突然忘记了时间格式怎么转换,特此做个记录 Java时间格式转换大全import java.text.*; import java.util.Calendar; public class VeDate ...
- [转载] Java中日期格式转换
参考链接: Java中的类型转换和示例 Code: /** * 字符串转换为java.util.Date<br> * 支持格式为 yyyy.MM.dd G 'at' hh: ...
- python批量读取图片并复制入word_提取word文档中的图片并使用Python进行批量格式转换,出,Word,里,利用,python...
日常工作中,你是否遇到过这样的场景,领导发来一份 Word 文档,要求你将文档中的图片存储到一个文件夹内,并且还要将图片都改成 .jpg 或者 .png,你会怎么办?你是不是一边内心崩溃,一边开始一张 ...
最新文章
- linux下批量修改文件名精彩解答案例分享
- 十四.200创业课程获得百万--不良,不要启动
- 20210614 什么是状态?什么是状态空间?
- 开课吧java_开课吧javaee企业级开发工程师 十期
- ASP.NET MVC5 ModelBinder
- 1734: [Usaco2005 feb]Aggressive cows 愤怒的牛
- RocketMq在windows下安装
- PyTorch-GPU版本、Tensorflow-GPU版本配置
- 有线电视与计算机网都是光缆吗,【有线电视论文】计算机管理有线电视光缆数据意义分析(共4443字)...
- 5G 与 WIFI6 的对比
- U3D Shader基础
- 训练好的vgg报错RuntimeError:mat1 and mat2 shapes cannot be multiplied(512*49 and 25088*4096)
- android 动画直播,直播动画实现方案一
- 干扰抑制 空时联合 matlab程序,空时联合自适应天线抗干扰的研究
- 数据结构和算法——kd树
- ACM顶会CIKM 2022放榜!度小满AI Lab三篇入选
- babylon.js实战教程
- 浅谈电磁学——高斯定理 环路定理
- PS透视模型动作插件:Perspective Mockups mac(支持ps2021)
- 2020G1工业锅炉司炉证考试及G1工业锅炉司炉作业模拟考试