转载请表明出处 https://blog.csdn.net/Amor_Leo/article/details/89389321 谢谢
Office转换pdf
jacob
下载jacob
jacob下载
下载后的压缩包中有两个dll文件,64位系统就用 x64的dll,32位系统就用x86的dll。将dll文件放入放入jdk/bin目录下.
把jacob.jar上传maven仓库
首先要配置maven环境变量,百度一大堆,我就不写了
将jacob.jar上传到maven仓库 命令如下: -Dfile 修改成你的jacob.jar所在目录
mvn install:install-file -Dfile=D:/workspace/jacob.jar -DgroupId=com.jacob -DartifactId=jacob -Dversion=1.19 -Dpackaging=jar
工具类
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.19</version>
</dependency>
public class ConvertPDFUtils {
private static Logger logger = LoggerFactory.getLogger(ConvertPDFUtils.class);
/**
* @Description: word转换pdf wps KWPS.Application
* @method: doc2pdf
* @Param: srcFilePath
* @Param: pdfFilePath
* @return: void
* @auther: LHL
* @Date: 2019/3/28 16:36
*/
public static int doc2pdf(String srcFilePath, String pdfFilePath) {
ActiveXComponent app = null;
Dispatch doc = null;
try {
ComThread.InitSTA();
//打开Word应用程序
app = new ActiveXComponent("Word.Application"); //office
//app = new ActiveXComponent("KWPS.Application"); //wps
//TODO
logger.debug("开始转化Word为PDF...");
long date = System.currentTimeMillis();
// 设置Word不可见
app.setProperty("Visible", false);
// 获得Word中所有打开的文档,返回documents对象
Dispatch docs = app.getProperty("Documents").toDispatch();
Object[] obj = new Object[]{
srcFilePath,
//是否只读
new Variant(true),
new Variant(true),
new Variant(false),
new Variant("pwd")
};
// 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
doc = Dispatch.invoke(docs, "Open", Dispatch.Method, obj, new int[1]).toDispatch();
//兼容性检查,为特定值false不正确
// Dispatch.put(doc, "Compatibility", false);
Dispatch.put(doc, "RemovePersonalInformation", false);
deletePdfFile(pdfFilePath);
// word保存为pdf格式宏,值为17
Dispatch.call(doc, "ExportAsFixedFormat", pdfFilePath, FileConstants.WORD_TO_PDF_OPERAND);
//TODO
logger.debug("doc: " + doc);
long date2 = System.currentTimeMillis();
int time = (int) ((date2 - date) / 1000);
logger.debug("用时:" + time);
return time;
} catch (Exception e) {
e.printStackTrace();
// throw e;
logger.debug("Exception" + e);
return -1;
} finally {
if (doc != null) {
// 关闭文档
Dispatch.call(doc, "Close", false);
}
if (app != null) {
// 关闭Word应用程序
app.invoke("Quit", 0);
}
ComThread.Release();
}
}
/**
* @Description: ppt转换pdf office2007以上版本PPT是不能转成PDF 最好使用wps
* @method: ppt2pdf
* @Param: srcFilePath
* @Param: pdfFilePath
* @return: void
* @auther: LHL
* @Date: 2019/3/28 16:36
*/
public static int ppt2pdf(String srcFilePath, String pdfFilePath) {
ActiveXComponent app = null;
Dispatch ppt = null;
try {
ComThread.InitSTA();
// app = new ActiveXComponent("PowerPoint.Application"); //Office
app = new ActiveXComponent("KWPP.Application"); //WPS
//TODO
logger.debug("开始转化PPT为PDF...");
long date = System.currentTimeMillis();
Dispatch ppts = app.getProperty("Presentations").toDispatch();
ppt = Dispatch.call(ppts, "Open", srcFilePath,
// ReadOnly
true,
// Untitled指定文件是否有标题
true,
// WithWindow指定文件是否可见
false
).toDispatch();
deletePdfFile(pdfFilePath);
// ppSaveAsPDF为特定值32
// Dispatch.call(ppt, "SaveAs", pdfFilePath, PPT_TO_PDF_OPERAND);
Object[] obj = new Object[]{
pdfFilePath,
new Variant(FileConstants.PPT_TO_PDF_OPERAND)
};
Dispatch.invoke(ppt, "SaveAs", Dispatch.Method, obj, new int[1]);
long date2 = System.currentTimeMillis();
int time = (int) ((date2 - date) / 1000);
logger.debug("用时:" + time);
return time;
} catch (Exception e) {
e.printStackTrace();
// throw e;
logger.debug("Exception" + e);
return -1;
} finally {
if (ppt != null) {
Dispatch.call(ppt, "Close");
}
if (app != null) {
app.invoke("Quit");
}
ComThread.Release();
}
}
/**
* @Description: excel转换pdf 如果超出一定列,会出现格式问题
* @method: excel2Pdf
* @Param: inFilePath
* @Param: outFilePath
* @return: void
* @auther: LHL
* @Date: 2019/3/28 16:38
*/
public static int excel2Pdf(String inFilePath, String outFilePath) {
ActiveXComponent ax = null;
Dispatch excel = null;
try {
ComThread.InitSTA();
ax = new ActiveXComponent("Excel.Application"); //office
// ax = new ActiveXComponent("KET.Application"); //wps
//TODO
logger.debug("开始转化Excel为PDF...");
long date = System.currentTimeMillis();
ax.setProperty("Visible", new Variant(false));
// 禁用宏
ax.setProperty("AutomationSecurity", new Variant(3));
Dispatch excels = ax.getProperty("Workbooks").toDispatch();
Object[] obj = new Object[]{
inFilePath,
new Variant(false),
new Variant(false)
};
excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();
deletePdfFile(outFilePath);
// 转换格式
Object[] obj2 = new Object[]{
// PDF格式=0
new Variant(FileConstants.EXCEL_TO_PDF_OPERAND),
outFilePath,
//0=标准 (生成的PDF图片不会变模糊) ; 1=最小文件 (生成的PDF图片糊的一塌糊涂)
new Variant(0)
};
Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, obj2, new int[1]);
long date2 = System.currentTimeMillis();
int time = (int) ((date2 - date) / 1000);
logger.debug("用时:" + time);
return time;
} catch (Exception es) {
es.printStackTrace();
// throw es;
logger.debug("Exception" + es);
return -1;
} finally {
if (excel != null) {
Dispatch.call(excel, "Close", new Variant(false));
}
if (ax != null) {
ax.invoke("Quit", new Variant[]{});
ax = null;
}
ComThread.Release();
}
}
/**
* @Description: 如果pdf文件存在, 删除
* @method: deletePdfFile
* @Param: pdfFilePath
* @return: void
* @auther: LHL
* @Date: 2019/3/29 9:35
*/
private static void deletePdfFile(String pdfFilePath) {
File tofile = new File(pdfFilePath);
if (tofile.exists()) {
tofile.delete();
}
}
/**
* @Description: 判断需要转化文件的类型(Excel、Word、ppt)
* @method: convert2PDF
* @Param: inputFile
* @Param: pdfFile
* @return: int
* @auther: LHL
* @Date: 2019/3/28 16:51
*/
public static int convert2PDF(String inputFile, String pdfFile) {
//判断文件类型
String kind = getFileSufix(inputFile);
File file = new File(inputFile);
if (!file.exists()) {
//文件不存在
return -2;
}
if (FileConstants.PDF.equals(kind)) {
//原文件就是PDF文件
return -3;
}
switch (kind) {
case FileConstants.WORD_DOC:
case FileConstants.WORD_DOCX:
case FileConstants.WORD_TXT:
case FileConstants.WORD_TEXT:
return ConvertPDFUtils.doc2pdf(inputFile, pdfFile);
case FileConstants.PPT_PPT:
case FileConstants.PPT_PPTX:
return ConvertPDFUtils.ppt2pdf(inputFile, pdfFile);
case FileConstants.EXCEL_XLS:
case FileConstants.EXCEL_XLSX:
case FileConstants.EXCEL_XLSM:
return ConvertPDFUtils.excel2Pdf(inputFile, pdfFile);
default:
return -4;
}
}
/**
* @Description: 判断文件类型
* @method: getFileSufix
* @Param: fileName
* @return: java.lang.String
* @auther: LHL
* @Date: 2019/3/28 16:51
*/
public static String getFileSufix(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(splitIndex + 1);
}
// public static void main(String[] args) {
// int time = convert2PDF("D:/222.pptx", "D:/ccc.pdf");
// if (time == -4) {
// System.out.println("转化失败,未知错误...");
// } else if (time == -3) {
// System.out.println("原文件就是PDF文件,无需转化...");
// } else if (time == -2) {
// System.out.println("转化失败,文件不存在...");
// } else if (time == -1) {
// System.out.println("转化失败,请重新尝试...");
// } else if (time < -4) {
// System.out.println("转化失败,请重新尝试...");
// } else {
// System.out.println("转化成功,用时: " + time + "s...");
// }
// }
oppenOffice
下载 oppenOffice
下载 jodconverter-core-3.0-beta-4.jar
jodconverter-core-3.0-beta-4.jar下载
由于是在国外网站找得到,我就弄个网盘链接
网盘链接 提取码:0fxn
jar包上传maven
- 将jodconverter-core-3.0-beta-4.jar上传到maven仓库 命令如下:-Dfile 修改成你的jodconverter-core-3.0-beta-4.jar所在目录
mvn install:install-file -Dfile=E:/Code/jodconverter-core-3.0-beta-4.jar -DgroupId=org.artofsolving.jodconverter -DartifactId=jodconverter-core -Dversion=3.0-beta-4 -Dpackaging=jar
- 再把commons-cli-1.1.jar,commons-io-1.4.jar,json-20090211.jar,juh-3.2.1.jar,jurt-3.2.1.jar,ridl-3.2.1.jar,unoil-3.2.1.jar放入你刚刚上传将jodconverter到maven仓库里的目录里的当前目录 我的是C:\Repository\org\artofsolving\jodconverter\jodconverter-core\3.0-beta-4\
工具类
<dependency>
<groupId>org.artofsolving.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>3.0-beta-4</version>
</dependency>
@Component
public class Office2PDFUtils {
private static Logger logger = LoggerFactory.getLogger(Office2PDFUtils.class);
@Value("${oppenOffice.path}")
private String path;
@Value("${oppenOffice.port}")
private int port;
/**
* 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件
* 调用该方法即可
* @param inputFilePath 源文件路径,如:"e:/test.docx"
* @return
*/
public boolean openOfficeToPDF(String inputFilePath, String outputFilePath_end) {
return office2pdf(inputFilePath,outputFilePath_end);
}
/**
* 根据操作系统的名称,获取OpenOffice.org 的安装目录
* @return OpenOffice.org 的安装目录
*/
public String getOfficeHome() {
String osName = System.getProperty("os.name");
System.out.println("操作系统名称:" + osName);
if (Pattern.matches("Linux.*", osName)) {
return path;
} else if (Pattern.matches("Windows.*", osName)) {
return path;
} else if (Pattern.matches("Mac.*", osName)) {
return path;
}
return null;
}
//public String getOfficeHome() {
// String osName = System.getProperty("os.name");
// if (Pattern.matches("Linux.*", osName)) {
// return "/opt/openoffice.org3";
// } else if (Pattern.matches("Windows.*", osName)) {
// return "D:/Program Files/OpenOffice.org 3";
// } else if (Pattern.matches("Mac.*", osName)) {
// return "/Application/OpenOffice.org.app/Contents";
// }
// return null;
//}
/**
* 连接OpenOffice.org 并且启动OpenOffice.org
*/
public OfficeManager getOfficeManager() {
DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
// 设置OpenOffice.org 的安装目录
String officeHome = getOfficeHome();
logger.debug("OpenOffice.org 的安装目录"+officeHome);
config.setOfficeHome(officeHome);
//设置端口号
logger.debug("OpenOffice.org 的端口"+port);
config.setPortNumber(port);
//设置任务执行超时为15分钟
config.setTaskExecutionTimeout(1000 * 60 * 15L);
//设置任务队列超时为24小时
config.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
// 启动OpenOffice的服务
OfficeManager officeManager = config.buildOfficeManager();
officeManager.start();
return officeManager;
}
/**
* 转换文件
*/
public File converterFile(File inputFile, String outputFilePath_end, String inputFilePath,OfficeDocumentConverter converter) {
File outputFile = new File(outputFilePath_end);
// 假如目标路径不存在,则新建该路径
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
converter.convert(inputFile, outputFile);
logger.debug("文件:" + inputFilePath + "\n转换为\n目标文件:" + outputFile + "\n成功!");
return outputFile;
}
/**
* 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件<br>
* @param inputFilePath 源文件路径
* @param outputFilePath_end 目标文件路径
* @return
*/
public boolean office2pdf(String inputFilePath, String outputFilePath_end) {
OfficeManager officeManager = null;
try {
if (StringUtils.isEmpty(inputFilePath)) {
logger.debug("输入文件地址为空,转换终止!");
return false;
}
File inputFile = new File(inputFilePath);
if (!inputFile.exists()) {
logger.debug("输入文件不存在,转换终止!");
return false;
}
File output = new File(outputFilePath_end);
if (output.exists()) {
logger.debug("输出文件存在,删除!");
output.delete();
}
// 获取OpenOffice的安装路劲
officeManager = getOfficeManager();
// 连接OpenOffice
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
File file = converterFile(inputFile, outputFilePath_end, inputFilePath, converter);
if (!file.exists()){
logger.debug("转换文件不存在!转换失败!!");
return false;
}
return true;
} catch (Exception e) {
logger.debug("转化出错!", e);
return false;
} finally {
// 停止openOffice
if (officeManager != null) {
officeManager.stop();
}
}
}
/**
* 获取inputFilePath的后缀名
*/
public String getPostfix(String inputFilePath) {
return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
}
}
yml
oppenOffice:
path: D:/SoftWare/OpenOffice
port: 9200