java springboot 实现DOC, DOCX, OOXML, RTF HTML, OpenDocument转PDF 实现word转pdf 在线预览
pom添加依赖
com.aspose
aspose-words
15.8.0
system
${project.basedir}/lib/lib/aspose-words-15.8.0-jdk16.jar
word转pdf 实现
package com.rainfe.common;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.rainfe.mapletr.common.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* @ClassName: FileUtils
* @Description
* @Author wpf
* @Date 2022/10/20
* @Version 1.0
*/
@Component
public class FileUtils {
public static String fileRootPath;
@Value("${fileRootPath}")
public void setFileRootPath(String fileRootPath) {
FileUtils.fileRootPath = fileRootPath;
}
public String getFileRootPath() {
return fileRootPath;
}
public JSONObject saveFile(MultipartFile file, String path) {
File rootPathDir = new File(fileRootPath);
if (!rootPathDir.exists()) {
rootPathDir.mkdirs();
}
String originalFilename = file.getOriginalFilename();
// 存储路径
String filePath = fileRootPath + path;
File file1 = new File(filePath);
if (!file1.exists()) {
file1.mkdirs();
}
String fileType = "";
int i = originalFilename.lastIndexOf(".");
if (i > 0) {
fileType = originalFilename.substring(i);
}
String fileId = UUID.randomUUID().toString();
String fileNewName = fileId + fileType;
filePath = filePath + fileNewName;
try {
// 保存文件
file.transferTo(new File(filePath));
} catch (IOException e) {
throw new DreamatsException("文件保存失败");
}
JSONObject jsonObject = new JSONObject();
long size = file.getSize();
jsonObject.put("id", fileId);
jsonObject.put("size", size);
jsonObject.put("name", originalFilename);
jsonObject.put("filename", fileNewName);
// 去掉根路径
jsonObject.put("path", filePath.substring(filePath.indexOf(fileRootPath) + fileRootPath.length()));
return jsonObject;
}
public void delFile(String path) {
// 存储路径
String filePath = fileRootPath + path;
File file1 = new File(filePath);
if (file1.exists()) {
file1.delete();
}
}
public void downFile(String filepath, String fileName, HttpServletResponse response) throws IOException {
if (!filepath.startsWith(fileRootPath)) {
filepath = fileRootPath + filepath;
}
//文件路径不存在时,自动创建目录
File file1 = new File(filepath);
if (!file1.exists()) {
throw new DreamatsException("要下载的文件不存在!");
}
// 清空缓冲区,状态码和响应头(headers)
response.reset();
// 设置ContentType,响应内容为二进制数据流,编码为utf-8,此处设定的编码是文件内容的编码
response.setContentType("application/octet-stream;charset=utf-8");
if (StringUtils.hasText(fileName)) {
//文件名转码
fileName = URLEncoder.encode(fileName, "UTF-8");
//3.设置content-disposition响应头控制浏览器以下载的形式打开文件
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), StandardCharsets.UTF_8));
}
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(filepath);
bis = new BufferedInputStream(fis);
// 获取字节流
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
throw new DreamatsException("下载发生异常!");
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public JSONArray saveManyFile(MultipartFile[] files, String path) {
JSONArray jsonArray = new JSONArray();
for (MultipartFile file : files) {
JSONObject jsonObject = saveFile(file, path);
jsonArray.add(jsonObject);
}
return jsonArray;
}
public void romveFile(String path) {
FileUtil.deleteFile(fileRootPath + path);
}
public void docToPdf(HttpServletResponse response, String filePath) throws IOException {
long startTime = System.nanoTime(); // 获取开始时间
System.out.println("开始时间:"+startTime);
String outputFileName = "output.pdf";
String pdffile = fileRootPath + filePath;
if (StringUtils.hasText(pdffile)) {
int i = pdffile.lastIndexOf(".");
pdffile = pdffile.substring(0, i+1) + "pdf";
}
OutputStream outStream = null;
try {
response.setContentType("application/pdf;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + outputFileName + "\"");
outStream = response.getOutputStream();
File file = new File( pdffile);
if (!file.exists()) {
// Load Word document
if (!getLicense()) {
return;
}
com.aspose.words.Document doc = new com.aspose.words.Document(fileRootPath + filePath);
// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
doc.save(pdffile, SaveFormat.PDF);
}
outStream.write(FileUtil.readFileToByteArray(file));
// Set response headers
// Convert Word to PDF and write to HTTP response stream
long endTime = System.nanoTime(); // 获取结束时间
long durationNs = endTime - startTime; // 计算耗时(单位:纳秒)
// 将纳秒转换为秒
double durationSeconds = TimeUnit.SECONDS.convert(durationNs, TimeUnit.NANOSECONDS);
System.out.printf("word转pdf用时: %.3f seconds", durationSeconds);
// Close the document (not necessary with try-with-resources)
// document.close();
} catch (Exception e) {
// Handle errors
e.printStackTrace();
response.getOutputStream().write("Failed to convert Word to PDF".getBytes());
// response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to convert Word to PDF");
} finally {
if (outStream != null) {
outStream.flush();
outStream.close();
}
}
}
public boolean getLicense() {
boolean result = false;
try {
// license.xml应放在..\WebRoot\WEB-INF\classes路径下
InputStream is = this.getClass().getClassLoader().getResourceAsStream("license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
license.xml
Aspose.Total for Java
Aspose.Words for Java
Enterprise
20991231
20991231
8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7
sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
调用 传入需要转换的word文件路径
@RequestMapping(value = "/docToPdf")
public void docToPdf(HttpServletResponse response, @RequestParam(value = "filepath") String filepath) throws IOException {
fileUtils.docToPdf(response, filepath);
}