package com.jeesite.modules.common.utils;
import org.jodconverter.office.DefaultOfficeManagerBuilder;
import org.jodconverter.office.OfficeException;
import org.jodconverter.office.OfficeManager;
public class OfficeManagerUtils {
/**
*
* @return 返回一个OfficeManager实例,用于处理转换业务
* @throws OfficeException
*/
static OfficeManager getOfficeManager() throws OfficeException {
DefaultOfficeManagerBuilder builder=new DefaultOfficeManagerBuilder();
//此处入参可以填写OpenOffice安装路径,本例子中,openOffice安装在E盘
//builder.setOfficeHome("D:/Program Files (x86)/OpenOffice 4");
builder.setOfficeHome("/opt/openoffice4");
OfficeManager officeManager =builder.build();
//officeManager提供了开启OpenOffice的API服务
officeManager.start();
return officeManager;
}
}
package com.jeesite.modules.common.utils;
import org.jodconverter.OfficeDocumentConverter;
import org.jodconverter.office.OfficeException;
import org.jodconverter.office.OfficeManager;
import java.io.File;
import static com.jeesite.modules.common.utils.OfficeManagerUtils.getOfficeManager;
public class OfficeDocumentConverterUtils {
public static File openOfficeExperience(String sourceFilePath){
OfficeManager officeManager = null;
String name="convertFile.pdf";
File outputFile=new File(name);
try {
//开启OpenOffice服务
OfficeManager manage=getOfficeManager();
File sourceFile = new File(sourceFilePath);
//设置转换后的文件存储路径,文件名
//使用OfficeDocumentConverter类转换文件,其实核心就这一句
OfficeDocumentConverter converter=new OfficeDocumentConverter(manage);
converter.convert(sourceFile,outputFile);
}catch(Exception e) {
e.printStackTrace();
}finally {
//关闭资源占用
if(officeManager != null){
try {
officeManager.stop();
} catch (OfficeException e) {
e.printStackTrace();
}
}
}
return outputFile;
}
}
上面工具类
service层
try {
String outPath = AsposeUtil.OfficeToPdf(url);
InputStream in = FileConvertUtil.convertLocaleFile(url, suffix);
File outputFile = new File(outPath);
InputStream in = new FileInputStream(outputFile);
OutputStream outputStream = response.getOutputStream();
// 创建存放文件内容的数组
byte[] buff = new byte[1024];
// 所读取的内容使用n来接收
int n;
// 当没有读取完时,继续读取,循环
while ((n = in.read(buff)) != -1) {
// 将字节数组的数据全部写入到输出流中
outputStream.write(buff, 0, n);
}
// 强制将缓存区的数据进行输出
outputStream.flush();
// 关闭流
outputStream.close();
in.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
前端点击事件 通过controller 调service