springboot word excel ppt 图片aspose 转换PDF 在线预览_jar

springboot word excel ppt 图片aspose 转换PDF 在线预览_工具类_02

springboot word excel ppt 图片aspose 转换PDF 在线预览_ide_03


springboot word excel ppt 图片aspose 转换PDF 在线预览_在线预览_04

文章目录

  • ​​1. 引入依赖​​
  • ​​2. 注册工具类​​
  • ​​3. 文件转换工具类​​
  • ​​4. 文件预览工具类​​
  • ​​5. 文件处理实现类​​
  • ​​6. 文件处理入口​​
  • ​​7. 配置类​​
  • ​​8. 配置文件​​
  • ​​9. 依赖目录+文件列表​​
  • ​​10. 图片转换工具类​​
  • ​​11. 测试连接​​
  • ​​12. 效果图​​
  • ​​12. 执行shell命令工具类补充​​
1. 引入依赖

下载 Aspose 的依赖 Jar 包可以通过一下仓库下载:​​Aspose 依赖下载​

springboot word excel ppt 图片aspose 转换PDF 在线预览_工具类_05

https://repository.aspose.com/repo/com/aspose/
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>

<dependency>
<groupId>com.aspose.cells</groupId>
<artifactId>aspose-cells</artifactId>
<version>22.6</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-22.6.jar</systemPath>
</dependency>

<dependency>
<groupId>com.aspose.words</groupId>
<artifactId>aspose-words</artifactId>
<version>words-22.5-jdk17</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-22.5-jdk17.jar</systemPath>
</dependency>

<dependency>
<groupId>aspose-slides</groupId>
<artifactId>aspose-slides</artifactId>
<version>slides-21.10-jdk16</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-slides-21.10-jdk16.jar</systemPath>
</dependency>

<dependency>
<groupId>aspose-pdf</groupId>
<artifactId>aspose-pdf</artifactId>
<version>pdf-21.7</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-pdf-21.7.jar</systemPath>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- web支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2. 注册工具类
package com.gblfy.office.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Date;

/**
* aspose 注册
* 仅供用于学习和交流,请勿做任何商业用途
*
* @author xieqiumin
* @since 2022-07-14
*/
public abstract class AsposeRegister {
/**
* aspose-words:jdk17:22.5 版本
*/
public static void registerWord_v_22_5() throws Exception {
Class<?> zzjXClass = Class.forName("com.aspose.words.zzjX");
Constructor<?> constructor = zzjXClass.getDeclaredConstructors()[0];
constructor.setAccessible(true);
Object zzjXInstance = constructor.newInstance();

// zzZ7O
Field zzZ7O = zzjXClass.getDeclaredField("zzZ7O");
zzZ7O.setAccessible(true);
zzZ7O.set(zzjXInstance, new Date(Long.MAX_VALUE));

// zzBf
Field zzZfB = zzjXClass.getDeclaredField("zzZfB");
zzZfB.setAccessible(true);
Class<?> zzYP3Class = Class.forName("com.aspose.words.zzYP3");
Field zzBfField = zzYP3Class.getDeclaredField("zzBf");
zzBfField.setAccessible(true);
zzZfB.set(zzjXInstance, zzBfField.get(null));

// zzZjA
Field zzZjA = zzjXClass.getDeclaredField("zzZjA");
zzZjA.setAccessible(true);
zzZjA.set(null, zzjXInstance);


Class<?> zzCnClass = Class.forName("com.aspose.words.zzCn");
Field zzZyx = zzCnClass.getDeclaredField("zzZyx");
zzZyx.setAccessible(true);
zzZyx.set(null, 128);
Field zzZ8w = zzCnClass.getDeclaredField("zzZ8w");
zzZ8w.setAccessible(true);
zzZ8w.set(null, false);
}

/**
* aspose-cells:22.6 版本有效
*/
public static void registerExcel_v_22_6() throws Exception {
String licenseExpiry = "20991231";

// License
Class<?> licenseClass = Class.forName("com.aspose.cells.License");
Field a = licenseClass.getDeclaredField("a");
a.setAccessible(true);
a.set(null, licenseExpiry);

// k65
Class<?> k65Class = Class.forName("com.aspose.cells.k65");
Field k65A = k65Class.getDeclaredField("a");
k65A.setAccessible(true);

Constructor<?> constructor = k65Class.getDeclaredConstructors()[0];
constructor.setAccessible(true);
Object k65Instance = constructor.newInstance();
k65A.set(null, k65Instance);

Field k56C = k65Class.getDeclaredField("c");
k56C.setAccessible(true);
k56C.set(k65Instance, licenseExpiry);

// e0n
Class<?> e0nClass = Class.forName("com.aspose.cells.e0n");
Field e0nA = e0nClass.getDeclaredField("a");
e0nA.setAccessible(true);
e0nA.set(null, false);

}

/**
* aspose-slides:21.10 版本有效
*/
public static void registerPPT_v_21_10() throws Exception {
Date licenseExpiry = new Date(Long.MAX_VALUE);

Class<?> publicClass = Class.forName("com.aspose.slides.internal.of.public");
Object publicInstance = publicClass.newInstance();

Field publicTry = publicClass.getDeclaredField("try");
publicTry.setAccessible(true);
publicTry.set(null, publicInstance);

Field publicInt = publicClass.getDeclaredField("int");
publicInt.setAccessible(true);
publicInt.set(publicInstance, licenseExpiry);

Field publicNew = publicClass.getDeclaredField("new");
publicNew.setAccessible(true);
publicNew.set(publicInstance, licenseExpiry);

Field publicIf = publicClass.getDeclaredField("if");
publicIf.setAccessible(true);
publicIf.set(publicInstance, 2);

Class<?> nativeClass = Class.forName("com.aspose.slides.internal.of.native");
Field nativeDo = nativeClass.getDeclaredField("do");
nativeDo.setAccessible(true);
nativeDo.set(null, publicInstance);
}

/**
* aspose-pdf:21.7 版本有效
*/
public static void registerPdf_v_21_7() throws Exception {
Date licenseExpiry = new Date(Long.MAX_VALUE);
Class<?> l9yClass = Class.forName("com.aspose.pdf.l9y");
Constructor<?> constructor = l9yClass.getDeclaredConstructors()[0];
constructor.setAccessible(true);
Object l9yInstance = constructor.newInstance();

// lc
Field lc = l9yClass.getDeclaredField("lc");
lc.setAccessible(true);
lc.set(l9yInstance, licenseExpiry);
// ly
Field ly = l9yClass.getDeclaredField("ly");
ly.setAccessible(true);
ly.set(l9yInstance, licenseExpiry);

// l0if
Field l0if = l9yClass.getDeclaredField("l0if");
l0if.setAccessible(true);

Class<?> l9nClass = Class.forName("com.aspose.pdf.l9n");
Field lfField = l9nClass.getDeclaredField("lf");
lfField.setAccessible(true);
Object lf = lfField.get(null); // 处理枚举
l0if.set(l9yInstance, lf);

Class<?> l9yLfClass = Class.forName("com.aspose.pdf.l9y$lf");
Field l9y$lf = l9yLfClass.getDeclaredField("lI");
l9y$lf.setAccessible(true);
l9y$lf.set(null, l9yInstance);


Class<?> l19jClass = Class.forName("com.aspose.pdf.l19j");
Field l19jlI = l19jClass.getDeclaredField("lI");
l19jlI.setAccessible(true);
l19jlI.set(null, 128);
Field l19jLf = l19jClass.getDeclaredField("lf");
l19jLf.setAccessible(true);
l19jLf.set(null, false);
}

public static void registerAll() {
try {
registerWord_v_22_5();
registerPPT_v_21_10();
registerExcel_v_22_6();
registerPdf_v_21_7();
} catch (Exception e) {
throw new RuntimeException("Aspose注册失败", e);
}

}
}
3. 文件转换工具类
package com.gblfy.office.utils;

import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;

/**
* 将office文件转成pdf
*
* @author gblfy
* @date 2022-11-05
*/
@Slf4j
@Component
public class PdfFileConvertUtil {

/**
* excel 转 pdf
*
* @param inputPath word文件path(全路径)
* @param outPath pdf文件path(全路径)
* @return
*/
public Boolean excel2pdf(String inputPath, String outPath) {
FileOutputStream os = null;
try {
AsposeRegister.registerExcel_v_22_6();
os = new FileOutputStream(outPath);
// Address是将要被转化的excel表格
Workbook workbook = new Workbook(inputPath);
workbook.save(os, com.aspose.cells.SaveFormat.PDF);
os.close();
return true;
} catch (Exception e) {
log.error("转换失败!", e);
if (os != null) {
try {
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return false;
}
}

/**
* ppt 转pdf
*
* @param inputPath
* @param outPath
* @return
*/
public Boolean ppt2pdf(String inputPath, String outPath) {
FileOutputStream os = null;
try {
AsposeRegister.registerPPT_v_21_10();
os = new FileOutputStream(outPath);
// Address是将要被转化的PPT幻灯片
Presentation pres = new Presentation(inputPath);
pres.save(os, com.aspose.slides.SaveFormat.Pdf);
os.close();
return true;
} catch (Exception e) {
log.error("转换失败!", e);
if (os != null) {
try {
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return false;
}
}

/**
* word 转 pdf
*
* @param inputPath word文件path(全路径)
* @param outPath pdf文件path(全路径)
* @return
*/
public Boolean word2pdf(String inputPath, String outPath) {
FileOutputStream os = null;
try {
AsposeRegister.registerWord_v_22_5();
os = new FileOutputStream(outPath);
Document doc = new Document(inputPath);
doc.save(os, SaveFormat.PDF);
os.close();
return true;
} catch (Exception e) {
log.error("转换失败!", e);
if (os != null) {
try {
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return false;
}
}
}
4. 文件预览工具类
package com.gblfy.office.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
* pdf在吸纳预览方法
*
* @author gblfy
* @date 2022-11-05
*/
public class PdfPreviewUtil {

/**
* 在线预览方法
* 把转换后的pdf文件在网页上进行预览
*
* @param response http响应
* @param previewFile 文件的決定路径 例:/app/20191009133209_chgrpt.pdf
* @throws Exception 格式转换过程中的异常
*/
public static void openPdf(HttpServletResponse response, String previewFile) throws Exception {
InputStream is = new FileInputStream(previewFile);
//响应文件的类型
response.setContentType("application/pdf");
response.setCharacterEncoding("UTF-8");
OutputStream os = response.getOutputStream();
int a = 0;
byte[] b = new byte[10 * 1024];
while ((a = is.read(b)) != -1) {
os.write(b, 0, a);
}
is.close();
os.close();
os.flush();
}



}
5. 文件处理实现类
package com.gblfy.office.impl;

import com.gblfy.office.utils.PdfFileConvertUtil;
import com.gblfy.office.utils.PdfPreviewUtil;
import com.gblfy.office.utils.PicUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
* office to pdf 预览
*
* @author gblfy
* @date 2022-11-05
*/
@Slf4j
@Component
public class PdfServiceImpl {
@Autowired
private PdfFileConvertUtil pdfFileConvertUtil;

@Value("${aspose.officeDir}")
private String officeDir;
@Value("${aspose.pdfDir}")
private String pdfDir;

/**
* 场景2:
* office原文件目录和转换后的pdf是非同一个目录
* office原文件名称和转换后的pdf是非同一个文件名称
*
* @param inputFileName
* @param response
*/
public void officeFileTopdf2(String inputFileName, HttpServletResponse response) {
// 记录文件处理~开始时间
long start = System.currentTimeMillis();
// 文件后缀
String suffix = inputFileName.substring(inputFileName.lastIndexOf(".") + 1);

try {
String officeFilePathAndFileName = officeDir + File.separator + inputFileName;
log.info("officeFilePathAndFileName->>>{}:", officeFilePathAndFileName);

// 初始化转换标志
Boolean flag = false;
// 初始化名称pdf
String pdfFileName = "";

// pdf文件校验
if ("pdf".equals(suffix)) {
pdfFileName = officeFilePathAndFileName;
flag = true;
log.info("pdfFileName ->>>{}:", pdfFileName);
}
// 非pdf文件校验
if (!"pdf".equals(suffix)) {
pdfFileName = pdfDir + File.separator + UUID.randomUUID().toString() + ".pdf";
log.info("pdfFileName ->>>{}:", pdfFileName);
}

// pdf文件名称和路径采用和原ofice文件目录和文件名称一样处理,根据实际情况特殊处理即可
if ("docx".equals(suffix)) {
flag = pdfFileConvertUtil.word2pdf(officeFilePathAndFileName, pdfFileName);
}
if ("doc".equals(suffix)) {
flag = pdfFileConvertUtil.word2pdf(officeFilePathAndFileName, pdfFileName);
}

if ("xlsx".equals(suffix)) {
flag = pdfFileConvertUtil.excel2pdf(officeFilePathAndFileName, pdfFileName);
}
if ("xls".equals(suffix)) {
flag = pdfFileConvertUtil.excel2pdf(officeFilePathAndFileName, pdfFileName);
}
if ("pptx".equals(suffix)) {
flag = pdfFileConvertUtil.ppt2pdf(officeFilePathAndFileName, pdfFileName);
}
if ("ppt".equals(suffix)) {
flag = pdfFileConvertUtil.ppt2pdf(officeFilePathAndFileName, pdfFileName);
}

if (flag) {
//预览pdf文件
PdfPreviewUtil.openPdf(response, pdfFileName);
}
} catch (Exception e1) {
e1.printStackTrace();
}
// 记录文件处理~完成时间
long end = System.currentTimeMillis();
// 文件处理~耗时时间计算
double castTime = (end - start) / 1000.0;
log.info("pdf转换成功,共耗时:->{}:", castTime);
}

/**
* 场景1:
* office原文件目录和转换后的pdf是同一个目录
* office原文件名称和转换后的pdf是同一个文件名称
*
* @param inputFileName
* @param response
*/
public void officeFileTopdf(String inputFileName, HttpServletResponse response) {
// 记录文件处理~开始时间
long start = System.currentTimeMillis();
// 文件后缀
String suffix = inputFileName.substring(inputFileName.lastIndexOf(".") + 1);

try {
String officeFilePathAndFileName = officeDir + File.separator + inputFileName;
log.info("officeFilePathAndFileName->>>{}:", officeFilePathAndFileName);

// 初始化转换标志
Boolean flag = false;
// 初始化名称pdf
String pdfFileName = "";

// pdf文件校验
if ("pdf".equals(suffix)) {
pdfFileName = officeFilePathAndFileName;
log.info("pdfFileName ->>>{}:", pdfFileName);
flag = true;
}

// pdf文件名称和路径采用和原ofice文件目录和文件名称一样处理,根据实际情况特殊处理即可
if ("docx".equals(suffix)) {
pdfFileName = officeFilePathAndFileName.replace(".docx", ".pdf");
log.info("pdfFileName ->>>{}:", pdfFileName);
flag = pdfFileConvertUtil.word2pdf(officeFilePathAndFileName, pdfFileName);
}
if ("doc".equals(suffix)) {
pdfFileName = officeFilePathAndFileName.replace(".doc", ".pdf");
log.info("pdfFileName ->>>{}:", pdfFileName);
flag = pdfFileConvertUtil.word2pdf(officeFilePathAndFileName, pdfFileName);
}

if ("xlsx".equals(suffix)) {
pdfFileName = officeFilePathAndFileName.replace(".xlsx", ".pdf");
log.info("pdfFileName ->>>{}:", pdfFileName);
flag = pdfFileConvertUtil.excel2pdf(officeFilePathAndFileName, pdfFileName);
}
if ("xls".equals(suffix)) {
pdfFileName = officeFilePathAndFileName.replace(".xls", ".pdf");
log.info("pdfFileName ->>>{}:", pdfFileName);
flag = pdfFileConvertUtil.excel2pdf(officeFilePathAndFileName, pdfFileName);
}
if ("pptx".equals(suffix)) {
pdfFileName = officeFilePathAndFileName.replace(".pptx", ".pdf");
log.info("pdfFileName ->>>{}:", pdfFileName);
flag = pdfFileConvertUtil.ppt2pdf(officeFilePathAndFileName, pdfFileName);
}
if ("ppt".equals(suffix)) {
pdfFileName = officeFilePathAndFileName.replace(".ppt", ".pdf");
log.info("pdfFileName ->>>{}:", pdfFileName);
flag = pdfFileConvertUtil.ppt2pdf(officeFilePathAndFileName, pdfFileName);
}

if ("jpg".equals(suffix)) {
pdfFileName = officeFilePathAndFileName.replace(".jpg", ".pdf");
log.info("pdfFileName ->>>{}:", pdfFileName);
flag = PicUtils.image2pdf(officeFilePathAndFileName, pdfFileName, suffix);
}
if ("png".equals(suffix)) {
pdfFileName = officeFilePathAndFileName.replace(".png", ".pdf");
log.info("pdfFileName ->>>{}:", pdfFileName);
flag = PicUtils.image2pdf(officeFilePathAndFileName, pdfFileName, suffix);
}

if (flag) {
//预览pdf文件
PdfPreviewUtil.openPdf(response, pdfFileName);
}
} catch (Exception e) {
e.printStackTrace();
}
// 记录文件处理~完成时间
long end = System.currentTimeMillis();
// 文件处理~耗时时间计算
double castTime = (end - start) / 1000.0;
log.info("pdf转换成功,共耗时:->{}:", castTime);
}
// /**
// * 场景1:
// * office原文件目录和转换后的pdf是同一个目录
// * office原文件名称和转换后的pdf是同一个文件名称
// *
// * @param inputFileName
// * @param response
// */
// public void officeFileTopdf(String inputFileName, HttpServletResponse response) {
// // 记录文件处理~开始时间
// long start = System.currentTimeMillis();
// // 文件后缀
// String suffix = inputFileName.substring(inputFileName.lastIndexOf(".") + 1);
//
// try {
// String officeFilePathAndFileName = officeDir + File.separator + inputFileName;
// log.info("officeFilePathAndFileName->>>{}:", officeFilePathAndFileName);
//
// // 初始化转换标志
// Boolean flag = false;
// // 初始化名称pdf
// String pdfFileName = "";
//
// // pdf文件校验
// if ("pdf".equals(suffix)) {
// pdfFileName = officeFilePathAndFileName;
// log.info("pdfFileName ->>>{}:", pdfFileName);
// flag = true;
// }
//
// // pdf文件名称和路径采用和原ofice文件目录和文件名称一样处理,根据实际情况特殊处理即可
// if ("docx".equals(suffix)) {
// pdfFileName = officeFilePathAndFileName.replace(".docx", ".pdf");
// log.info("pdfFileName ->>>{}:", pdfFileName);
// flag = pdfFileConvertUtil.word2pdf(officeFilePathAndFileName, pdfFileName);
// }
// if ("doc".equals(suffix)) {
// pdfFileName = officeFilePathAndFileName.replace(".doc", ".pdf");
// log.info("pdfFileName ->>>{}:", pdfFileName);
// flag = pdfFileConvertUtil.word2pdf(officeFilePathAndFileName, pdfFileName);
// }
//
// if ("xlsx".equals(suffix)) {
// pdfFileName = officeFilePathAndFileName.replace(".xlsx", ".pdf");
// log.info("pdfFileName ->>>{}:", pdfFileName);
// flag = pdfFileConvertUtil.excel2pdf(officeFilePathAndFileName, pdfFileName);
// }
// if ("xls".equals(suffix)) {
// pdfFileName = officeFilePathAndFileName.replace(".xls", ".pdf");
// log.info("pdfFileName ->>>{}:", pdfFileName);
// flag = pdfFileConvertUtil.excel2pdf(officeFilePathAndFileName, pdfFileName);
// }
// if ("pptx".equals(suffix)) {
// pdfFileName = officeFilePathAndFileName.replace(".pptx", ".pdf");
// log.info("pdfFileName ->>>{}:", pdfFileName);
// flag = pdfFileConvertUtil.ppt2pdf(officeFilePathAndFileName, pdfFileName);
// }
// if ("ppt".equals(suffix)) {
// pdfFileName = officeFilePathAndFileName.replace(".ppt", ".pdf");
// log.info("pdfFileName ->>>{}:", pdfFileName);
// flag = pdfFileConvertUtil.ppt2pdf(officeFilePathAndFileName, pdfFileName);
// }
// if (flag) {
// response.setCharacterEncoding("UTF-8");
// response.setContentType("application/pdf");
// byte[] buf = new byte[8 * 1024];
// int len = 0;
// try {
// InputStream is = new FileInputStream(pdfFileName);
// OutputStream os = response.getOutputStream();
// while ((len = is.read(buf, 0, buf.length)) != -1) {
// os.write(buf, 0, len);
// }
// is.close();
// os.close();
// os.flush();
// } finally {
// try {
// deleteFile(officeFilePathAndFileName);
// deleteFile(pdfFileName);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// // 记录文件处理~完成时间
// long end = System.currentTimeMillis();
// // 文件处理~耗时时间计算
// double castTime = (end - start) / 1000.0;
// log.info("pdf转换成功,共耗时:->{}:", castTime);
// }

// /**
// * 删除文件
// *
// * @param filePath 文件
// * @return
// */
// public static boolean deleteFile(String filePath) {
// boolean flag = false;
// File file = new File(filePath);
// // 路径为文件且不为空则进行删除
// if (file.isFile() && file.exists()) {
// file.delete();
// flag = true;
// }
// return flag;
// }
}
6. 文件处理入口
package com.gblfy.office.controller;

import com.gblfy.office.impl.PdfServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
* office file to pdf 预览
*
* @author gblfy
* @date 2022-11-05
*/
@RestController
public class PdfPreviewController {
@Autowired
private PdfServiceImpl pdfService;

/**
* 测试链接:
* http://localhost/officeFileTopdf/7-1207-26公司元旦放假通知范文Word模板.docx
* http://localhost/officeFileTopdf/20228751.xlsx
* http://localhost/officeFileTopdf/小清新PPT.pptx
* http://localhost/officeFileTopdf/预览图_千图网_编号35522533.jpg
*/
@GetMapping("/officeFileTopdf/{fileName}")
public void officeFileTopdf(@PathVariable String fileName, HttpServletResponse response) {
pdfService.officeFileTopdf(fileName, response);
}
}
7. 配置类
package com.gblfy.office.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* SpringMvc通用配置
*
* @author gblfy
* @date 2022-04-06
*/
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {

@Value("${local.path}")
private String path;

/**
* 文件上传路径配置
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/** 本地文件上传路径 */
registry.addResourceHandler("/f/**")
.addResourceLocations("file:" + path);
}

/**
* 跨域配置
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedHeaders(CorsConfiguration.ALL)
.allowedMethods(CorsConfiguration.ALL)
.allowCredentials(true)
.maxAge(3600); // 1小时内不需要再预检(发OPTIONS请求)
}

// 统一注解,解决前后端交互Long类型精度丢失的问题
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
//全局配置序列化返回json处理
SimpleModule simpleModule = new SimpleModule();
//json Long ==>String
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
8. 配置文件

application.yml

server:
port: 80
local:
path: D:/ht/outfile

aspose:
officeDir: D:/ht/officefile
pdfDir: D:/ht/outpdf
9. 依赖目录+文件列表

springboot word excel ppt 图片aspose 转换PDF 在线预览_ide_06

10. 图片转换工具类
package com.gblfy.office.utils;

import com.aspose.pdf.Document;
import com.aspose.pdf.Image;
import com.aspose.pdf.Page;
import com.aspose.pdf.SaveFormat;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
* 图片 to pdf 预览
*
* @author gblfy
* @date 2022-11-05
*/
public class PicUtils {

public static void main(String[] args) throws Exception {
String source = "D:\\ht\\officefile\\预览图_千图网_编号35522533.jpg";
String target = "D:\\ht\\officefile\\预览图_千图网_编号35522533.pdf";
image2pdf(source, target, "jpg");
}

/**
* 图片转PDF
*
* @param sourcePath
* @param targetPath
* @param imgType
* @throws IOException
*/
public static boolean image2pdf(String sourcePath, String targetPath, String imgType) {
ByteArrayOutputStream baos = null;
ByteArrayInputStream bais = null;
try {
AsposeRegister.registerPdf_v_21_7();
//创建文档
Document doc = new Document();
//新增一页
Page page = doc.getPages().add();
//设置页边距
page.getPageInfo().getMargin().setBottom(0);
page.getPageInfo().getMargin().setTop(0);
page.getPageInfo().getMargin().setLeft(0);
page.getPageInfo().getMargin().setRight(0);
//创建图片对象
Image image = new Image();
BufferedImage bufferedImage = ImageIO.read(new File(sourcePath));
//获取图片尺寸
int height = bufferedImage.getHeight();
int width = bufferedImage.getWidth();
baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, imgType, baos);
baos.flush();
bais = new ByteArrayInputStream(baos.toByteArray());
image.setImageStream(bais);
//设置pdf页的尺寸与图片一样
page.getPageInfo().setHeight(height);
page.getPageInfo().setWidth(width);
//添加图片
page.getParagraphs().add(image);
//保存
doc.save(targetPath, SaveFormat.Pdf);
baos.close();
bais.close();
return true;
} catch (Exception e) {
try {
baos.close();
bais.close();
e.printStackTrace();
return false;
} catch (IOException e2) {
e2.printStackTrace();
}
}
return false;
}

}
11. 测试连接
/**
* 测试链接:
* http://localhost/wordtopdf/7-1207-26公司元旦放假通知范文Word模板.docx
* http://localhost/wordtopdf/20228751.xlsx
* http://localhost/wordtopdf/小清新PPT.pptx
*/
12. 效果图

springboot word excel ppt 图片aspose 转换PDF 在线预览_jar_07

springboot word excel ppt 图片aspose 转换PDF 在线预览_工具类_02

springboot word excel ppt 图片aspose 转换PDF 在线预览_ide_03


springboot word excel ppt 图片aspose 转换PDF 在线预览_在线预览_04

12. 执行shell命令工具类补充
package com.gblfy.office.utils;

import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
* @@author gblfy
* @Date : 2022-11-05 11:20
* @describe: 文档在线预览
* <p>
* 服务器环境:Linux环境
* 现支持文档类型: Excel word ppt pdf
*/
public class ExecuteLinuxShellUtil {

private static ExecuteLinuxShellUtil linuxPageDIsplsyFileUtil;

public static synchronized ExecuteLinuxShellUtil getSwitchUtil() {
if (linuxPageDIsplsyFileUtil == null) {
linuxPageDIsplsyFileUtil = new ExecuteLinuxShellUtil();
}
return linuxPageDIsplsyFileUtil;
}

/**
* 文档在线预览
*
* @param response
* @param fileStoragePath 文件存储路径 (前段获取文件存储路径返给后台)
* @param beforeConversion 文件名(必须带文件后缀名,这里指的就是文件全名称)
* @throws Exception
*/
public void conversionFile(HttpServletResponse response, String fileStoragePath, String beforeConversion) throws Exception {
//文件存储路径
//fileStoragePath ="/app/";
//转换前的文件名
//beforeConversion ="20191009133209lis_chgrpt.docx";
String fileNamePath = fileStoragePath + beforeConversion;
File file = new File(fileNamePath);
if (!file.exists()) {
System.err.println("库存中没有指定文件。。。。");
return;
}
//获取到文件名
String interceptFileName = beforeConversion.substring(0, beforeConversion.lastIndexOf("."));
//截取文件后缀名
String fileNameSuffix = beforeConversion.substring(beforeConversion.lastIndexOf(".") + 1);
String command = null;
if ("pdf".equals(fileNameSuffix)) {
/**
* 在线预览方法
*/
PdfPreviewUtil.openPdf(response, fileStoragePath + interceptFileName + ".pdf");
} else if ("doc".equals(fileNameSuffix) || "docx".equals(fileNameSuffix)
|| "xls".equals(fileNameSuffix) || "xlsx".equals(fileNameSuffix)
|| "ppt".equals(fileNameSuffix) || "pptx".equals(fileNameSuffix)) {
//文件格式转换命令 unoconv插件实现
command = "/opt/libreoffice6.3/program/soffice --headless --invisible --convert-to pdf " + fileNamePath;
//格式转换+在线预览
formatConverAndPreview(command, response, fileStoragePath, interceptFileName);
} else {
System.err.println("暂不支持该类型文件在线预览!!!");
return;
}
}

/**
* 格式转换+在线预览 方法
*
* @param command 文件格式转换命令 例:/usr/bin/unoconv -f pdf /app/1.pptx
* @param response http响应网页,实现在线预览
* @param fileStoragePath 准备文件存放路径 例:/app/
* @param interceptFileName 文件名 例: 1.pptx
* @throws Exception
*/
public void formatConverAndPreview(String command,
HttpServletResponse response,
String fileStoragePath,
String interceptFileName) throws Exception {
/**
* 执行shell命令,格式转换方法
*/
//String temp ="/usr/bin/unoconv -f pdf " + command;
executeCommand(command);
/**
* 在线预览方法
*/
PdfPreviewUtil.openPdf(response, fileStoragePath + interceptFileName + ".pdf");
}


/**
* 执行shell命令
* <p>
* 統一把文件格式转换成pdf文件
*
* @param command 文件格式转换命令
* 例1:/usr/bin/unoconv -f pdf /app/1.pptx
* 例2:/opt/libreoffice6.3/program/soffice --headless --invisible --convert-to pdf /app/1.pptx
*/
private static void executeCommand(String command) {

StringBuffer output = new StringBuffer();
Process process;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
try {
process = Runtime.getRuntime().exec(command);
process.waitFor();
inputStreamReader = new InputStreamReader(process.getInputStream(), "UTF-8");
reader = new BufferedReader(inputStreamReader);
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
//p.destroy();//这个一般不需要
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(inputStreamReader);
}
}

}