第一步
服务器端要安装Apache的 openoffice,下载地址 :http://www.openoffice.org/download
第二步
OpenOffice 文件转换服务,调用接口,传入文件链接,返回转换成pdf的文件流。
如需要转换其他文件类型,可以自己在代码中修改,只需修改文件后缀,就可以转换成对应的文件类型。看下图
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.test</groupId>
<artifactId>officepreview</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-local -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<!-- poi库主要用来调整excel转pdf的格式调整(将所有列调整到一页) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
</dependencies>
</project>
OfficePreview.java 主要代码(主要是 toPdfFile 方法 )
package cn.test.office;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.office.OfficeUtils;
import org.jodconverter.core.util.IOUtils;
import org.jodconverter.core.util.StringUtils;
import org.jodconverter.local.JodConverter;
import org.jodconverter.local.office.LocalOfficeManager;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ResourceBundle;
@WebServlet(name = "officepreview")
public class OfficePreview extends HttpServlet {
private ResourceBundle rd = ResourceBundle.getBundle("office");
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
// 获取配置
String repositoryPath = rd.getString("repository");
// 远程文件路径(需要URLDecoder解码,解决存在中文字符问题)
String url = URLDecoder.decode(req.getParameter("url"), "utf-8");
// 转换后的文件名称
String filename = req.getParameter("filename");
// 下载到本地
downLoad(url, repositoryPath + filename);
// 转换文件,使用response,将pdf文件以流的方式发送的前端
FileInputStream fis = new FileInputStream(toPdfFile(repositoryPath + filename));
// copy文件流到输出流
IOUtils.copy(fis, resp.getOutputStream());
fis.close();
} catch (Exception e) {
e.printStackTrace();
try {
resp.getOutputStream().println(e.getMessage());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public File toPdfFile(String sourceFilePath) throws IOException, OfficeException {
String officeHomePath = rd.getString("officeHomePath");
boolean excelPreviewSetting = "1".equals(rd.getString("excelPreviewSetting"));
// 源文件
File sourceFile = new File(sourceFilePath);//转换之后文件生成的地址
// 如果路径地址不存在
if (!sourceFile.exists()) throw new RuntimeException("转换源文件不存在");
// 如果本身是pdf文件,就直接返回
if(sourceFile.getName().endsWith("pdf")) {
return sourceFile;
}
// 转换后的文件
File newFile = new File(String.format("%s\\%s", sourceFile.getParent(), sourceFile.getName().replace(".","")+".pdf"));
if (!newFile.exists()){ // 文件不存在,才需要转换
// 获取openoffice管理器
LocalOfficeManager localOfficeManager = LocalOfficeManager.builder().officeHome(officeHomePath).install().build();
// 判断openoffice服务是否打开
if(!localOfficeManager.isRunning()) localOfficeManager.start();
// 已开启预览设置,并且是xls文件
if (excelPreviewSetting && sourceFile.getName().endsWith("xls") || sourceFile.getName().endsWith("xlsx")){
// 获取调整预览格式后的文件
sourceFile = setExcelPrintParameter(sourceFile.getPath());
}
//文件转化
JodConverter.convert(sourceFile).to(newFile).execute();
// 关闭localOfficeManager服务
OfficeUtils.stopQuietly(localOfficeManager);
}
return newFile;
}
/**
* 文件下载
* @param url 远程文件链接
* @param downloadPath 本地路径
*/
private void downLoad(String url, String downloadPath){
BufferedInputStream bis =null;
BufferedOutputStream bos=null;
try {
// 判断路径合法性
if (StringUtils.isBlank(url)) return;
// 判断本地是否已存在该文件,已存在则不重复下载
if (new File(downloadPath).exists()) return;
int contentLength = getConnection(url).getContentLength();
System.out.println("文件的大小是:"+contentLength);
InputStream is= getConnection(url).getInputStream();
bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(downloadPath);
bos= new BufferedOutputStream(fos);
int b;
byte[] byArr = new byte[1024];
while((b= bis.read(byArr))!=-1){
bos.write(byArr, 0, b);
}
System.out.println("下载的文件的大小是----------------------------------------------:"+contentLength);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(bis !=null) bis.close();
if(bos !=null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private HttpURLConnection getConnection(String httpUrl) throws Exception {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.connect();
return connection;
}
/**
* 设置Excel打印参数
* @param sourceFilePath 源文件路径
*/
private File setExcelPrintParameter(String sourceFilePath) throws IOException{
File sourceFile = new File(sourceFilePath);
Workbook workbook = WorkbookFactory.create(new FileInputStream(sourceFile));
for (int i = 0; i < workbook.getNumberOfSheets(); i++){
Sheet sheet = workbook.getSheetAt(i);
sheet.setFitToPage(true);
PrintSetup printSetup = sheet.getPrintSetup();
printSetup.setFitWidth((short) 1);
//设置打印方向,横向就是true
printSetup.setLandscape(false);
//设置A4纸
printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
}
workbook.write(new FileOutputStream(sourceFile));
return sourceFile;
}
/**
* 在oldName基础上添加后缀suffix
* @param oldName 旧文件名
* @param suffix 后缀
* @return 返回新文件名
*/
public static String getNewFileName(String oldName, String suffix){
// 名字为空直接返回null
if (StringUtils.isEmpty(oldName)) return oldName;
// 获取点符号下标
int dotIndex = oldName.lastIndexOf('.');
// 如果没有点符号说明没有文件类型,直接添加suffix后缀
if (-1 == dotIndex) return oldName + suffix;
// 获取没有类型名称的文件名
String name = oldName.substring(0, dotIndex);
// 获取类型
String type = oldName.substring(dotIndex);
return name + suffix + type;
}
}
office.properties 配置属性文件
# 转换后文件存储路径
repository=I:\\test\\
# openoffice安装路径
officeHomePath=C:\\Program Files (x86)\\OpenOffice 4
# 是否开启excel预览格式调整 1=开启,0=关闭(将所有列调整到同一页)
excelPreviewSetting=0