1.首先下载相关jar包和dll:https://sourceforge.net/projects/jacob-project/files/jacob-project/1.17/
jar包和dll工具
2.如果是64位系统选择jacob-1.17-x64.dll文件,如果是32位系统,选择jacob-1.17-x86.dll文件,将dll文件分别放置到C:\Windows\System32目录下和C:\Program Files\Java\jre1.8.0_112\bin目录下。
3.确保电脑上已安装了wps软件。
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
public class Test {
private static final int wdFormatPDF = 17;
private static final int xlTypePDF = 0;
private static final int ppSaveAsPDF = 32;
public static void main(String[] args) {
if (new Test().convert2PDF("C:/DS1-1-1.pptx","C:/DS1-1-1.pdf"))
System.out.println("转换完成!");
else
System.out.println("转换失败!");
}
public boolean convert2PDF(String inputFile, String pdfFile) {
String suffix = getFileSufix(inputFile);
File file = new File(inputFile);
if (!file.exists()) {
return false;
}
if (suffix.equals("pdf")) {
return false;
}
if (suffix.equals("ppt") || suffix.equals("pptx")) {
System.out.println("begin:");
return ppt2PDF(inputFile, pdfFile);
} else {
return false;
}
return false;
}
public static String getFileSufix(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(splitIndex + 1);
}
// ppt转换为pdf
public static boolean ppt2PDF(String inputFile, String pdfFile) {
try {
ActiveXComponent app = new ActiveXComponent("KWPP.Application");
// app.setProperty("Visible", msofalse);
Dispatch ppts = app.getProperty("Presentations").toDispatch();
Dispatch ppt = Dispatch.call(ppts, "Open", inputFile, true, // ReadOnly
true, // Untitled指定文件是否有标题
false// WithWindow指定文件是否可见
).toDispatch();
Dispatch.call(ppt, "SaveAs", pdfFile, ppSaveAsPDF);
Dispatch.call(ppt, "Close");
app.invoke("Quit");
return true;
} catch (Exception e) {
return false;
}
}
}