项目中有这样一个需求,需要预览上传的ppt、word、excel文件
下面介绍几种方式实现预览
第一种
使用微软提供的Office Online平台只需要一个网址即可在线查看Xls,doc,PPT等文档
http://view.officeapps.live.com/op/view.aspx?src=要查看的文档地址
第二种
第三方渠道,个人觉得下面这个挺好用的,如果只是自己学习开发使用完全可以了
这个要注意一点 你开始传的示例文件 不付费的话有效期都很短而且有大小限制,4mb
XDOC文档预览服务移动端和PC端无插件预览PDF、OFD、Word、WPS等多种文档https://view.xdocin.com/
第三种
文档格式转换+aspose破解
也是最麻烦的一种,需要将源文件转为对应的pdf文件来实现预览文档,下面介绍一种个人觉得比较好使的转pdf方式
Aspose for Java提供了丰富的类和方法,允许开发者直接操作Office文档,例如创建、读取、修改和转换。对于PDF转换,Aspose.Words、Aspose.Cells和Aspose.Presentations分别处理Word、Excel和PowerPoint文档的转换。
引入相关的jar包,相关的jar包,暂时放在云盘上的
链接:百度网盘 请输入提取码
提取码:xs0f
导入相关依赖
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>18.6</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-18.6-jdk16.jar</systemPath>
</dependency>
<!-- ppt转pdf -->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-slides</artifactId>
<version>22.9</version>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-slides-22.9-jdk16.jar</systemPath>
<scope>system</scope>
</dependency>
<!-- excel转pdf -->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cells</artifactId>
<version>8.5.2</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-8.5.2.jar</systemPath>
</dependency>
工具类 FileTransForUtils
package com.ruoyi.common.utils.file;
import com.aspose.cells.Workbook;
import com.aspose.slides.IFontsManager;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.ruoyi.common.utils.obs.HuaWeiObsUtil;
import lombok.SneakyThrows;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class FileTransForUtils {
private static final Logger logger = LoggerFactory.getLogger(FileTransForUtils.class);
//word转PDF
public synchronized static boolean word3Pdf(String wordPath, String pdfPath) {
if (!getLicense("word")) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return false;
}
try {
long old = System.currentTimeMillis();
File file = new File(pdfPath); //新建一个pdf文档
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(wordPath); //Address是将要被转化的word文档
doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB,
// XPS, SWF 相互转换
long now = System.currentTimeMillis();
os.close();
logger.info("word共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
return true;
} catch (Exception e) {
logger.error(String.valueOf(e));
e.printStackTrace();
return false;
}
}
//excel转PDF
public synchronized static boolean excel3pdf(String excelPath, String pdfPath) {
if (!getLicense("excel")) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return false;
}
try {
long old = System.currentTimeMillis();
File pdfFile = new File(pdfPath); //新建一个pdf文档
FileOutputStream os = new FileOutputStream(pdfFile);
Workbook wb = new Workbook(excelPath);// 原始excel路径
wb.save(os,com.aspose.cells.SaveFormat.PDF);
long now = System.currentTimeMillis();
os.close();
logger.info("excel共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
return true;
} catch (Exception e) {
logger.error(String.valueOf(e));
e.printStackTrace();
return false;
}
}
/**
* 获取license 去除水印
* @return
*/
public static boolean getPPtLicense() {
boolean result = false;
try {
InputStream is = FileTransForUtils.class.getClassLoader().getResourceAsStream("\\license.xml");
com.aspose.slides.License aposeLic = new com.aspose.slides.License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//ppt转PDF
@SneakyThrows
public synchronized static boolean ppt3pdf(String pptPath, String pdfPath) {
// 验证License
if (!getLicense("ppt")) {
return false;
}
FileOutputStream os = null;
try {
long old = System.currentTimeMillis();
File pdfFile = new File(pdfPath); //新建一个pdf文档
os = new FileOutputStream(pdfFile);
Presentation pres = new Presentation(pptPath);//输入ppt路径
IFontsManager fontsManager = pres.getFontsManager();
pres.save(os,com.aspose.slides.SaveFormat.Pdf);
long now = System.currentTimeMillis();
logger.info("ppt共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
return true;
} catch (Exception e) {
logger.error(String.valueOf(e));
e.printStackTrace();
return false;
}finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//剔除水印
private static boolean getLicense(String type) {
boolean result = false;
String licenseFile = "license.xml";
if (type.equals("ppt")){
licenseFile = "license_22_9.xml";
}
try {
// 凭证
InputStream is = FileTransForUtils.class.getClassLoader().getResourceAsStream(licenseFile);
//InputStream is = new ByteArrayInputStream(license.getBytes("UTF-8"));
if(type.equals("word")){
License asposeLic = new License();
asposeLic.setLicense(is);
}else if (type.equals("excel")){
com.aspose.cells.License asposeLic = new com.aspose.cells.License();
asposeLic.setLicense(is);
}else if (type.equals("ppt")){
com.aspose.slides.License aposeLic = new com.aspose.slides.License();
aposeLic.setLicense(is);
}
result = true;
} catch (Exception e) {
logger.error(String.valueOf(e));
e.printStackTrace();
return false;
}
return result;
}
/**
* 判断资源类型文档类
*/
public static String getResourceTypesDocument(String suffix) {
String type = null;
switch (suffix) {
//文档类型
case ".doc":
case ".docx":
case ".txt":
type = "word";
break;
case ".xls":
case ".xlsx":
type = "excel";
break;
case ".ppt":
case ".pptx":
type = "ppt";
break;
case ".mp4":
case ".MP4":
type = "video";
break;
case ".pdf":
type = "pdf";
break;
case ".jpg":
case ".png":
case ".gif":
case ".bmp":
case ".jpeg":
case ".svg":
case ".ico":
case ".tiff":
type = "image";
break;
}
return type;
}
private static Map<String,Object> getFirstPageAsImgByPdf(String url){
Map<String,Object> result = new HashMap<>();
String res = null;
PDDocument pd = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<byte[]> response = restTemplate.getForEntity(url, byte[].class);
// 加载pdf文件
pd = PDDocument.load(new ByteArrayInputStream(response.getBody()));
// 准备pdf文件渲染对象
PDFRenderer pdfRenderer = new PDFRenderer(pd);
// 判断pdf页数
if (pd.getNumberOfPages() > 0) {
// 设置页数(首页从0开始)、每英寸点数、图片类型
BufferedImage bim = pdfRenderer.renderImageWithDPI(0, 96, ImageType.RGB);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 将图片写入到图片对象中
ImageIO.write(bim, "png", bos);
String base64Img = Base64Utils.encodeToString(bos.toByteArray());
res = "data:image/jpg;base64," + base64Img;
result.put("flag",true);
result.put("message",res);
return result;
}
result.put("flag",false);
result.put("message","文件页数为0,请上传正确的文件");
return result;
} catch (Exception ex) {
result.put("flag",false);
result.put("message","获取pdf首页作为图片失败");
return result;
}
}
}
这里需要俩个文件,具体原因是因为,aspose-slides-15.9.0在解析部分pptx文件的时候会卡死,导致后续文档都无法转码,所以建议使用22.9的
<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>
<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>
准备工作就完成了,开始开始转码了
public static void main(String[] args) {
String filePath = "D:/video/test.pptx";
String suffix = filePath.substring(filePath.lastIndexOf("."));
String type = FileTransForUtils.getResourceTypesDocument(suffix);
String pdfPath = "D:/video/test.pdf";
if("ppt".equals(type)){
FileTransForUtils.ppt3pdf(filePath,pdfPath);
}else if("word".equals(type)){
FileTransForUtils.word3Pdf(filePath,pdfPath);
}else if("excel".equals(type)){
FileTransForUtils.excel3pdf(filePath,pdfPath);
}
}
转码成功后,就可以使用pdf实现预览了