引入的包
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
定义的全局变量
private static final Integer WORD_TO_PDF_OPERAND = 17;
private static final Integer PPT_TO_PDF_OPERAND = 32;
private static final Integer EXCEL_TO_PDF_OPERAND = 0;
word转pdf
public static void doc2Pdf(String srcFilePath, String pdfFilePath) throws Exception {
ActiveXComponent app = null;
Dispatch doc = null;
try {
ComThread.InitSTA();
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);
Dispatch docs = app.getProperty("Documents").toDispatch();
Object[] obj = new Object[]{
srcFilePath,
new Variant(false),
new Variant(false),
new Variant(false),
new Variant("pwd")
};
doc = Dispatch.invoke(docs, "Open", Dispatch.Method, obj, new int[1]).toDispatch();
File tofile = new File(pdfFilePath);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.put(doc, "RemovePersonalInformation", false);
Dispatch.call(doc, "ExportAsFixedFormat", pdfFilePath, WORD_TO_PDF_OPERAND);
}catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (doc != null) {
Dispatch.call(doc, "Close", false);
}
if (app != null) {
app.invoke("Quit", 0);
}
ComThread.Release();
}
}
ppt转PDF
public static void ppt2Pdf(String srcFilePath, String pdfFilePath) throws Exception {
ActiveXComponent app = null;
Dispatch ppt = null;
try {
ComThread.InitSTA();
app = new ActiveXComponent("PowerPoint.Application");
Dispatch ppts = app.getProperty("Presentations").toDispatch();
File tofile = new File(pdfFilePath);
if (tofile.exists()) {
tofile.delete();
}
ppt = Dispatch.call(ppts, "Open", srcFilePath, true,true, false).toDispatch();
Dispatch.call(ppt, "SaveAs", pdfFilePath, PPT_TO_PDF_OPERAND);
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (ppt != null) {
Dispatch.call(ppt, "Close");
}
if (app != null) {
app.invoke("Quit");
}
ComThread.Release();
}
}
excel转Pdf
public static void excel2Pdf(String inFilePath, String outFilePath) throws Exception {
ActiveXComponent ax = null;
Dispatch excel = null;
try {
ComThread.InitSTA();
ax = new ActiveXComponent("Excel.Application");
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)
};
File tofile = new File(outFilePath);
if (tofile.exists()) {
tofile.delete();
}
excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();
Object[] obj2 = new Object[]{
new Variant(EXCEL_TO_PDF_OPERAND),
outFilePath,
new Variant(0)
};
Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method,obj2, new int[1]);
} catch (Exception es) {
es.printStackTrace();
throw es;
} finally {
if (excel != null) {
Dispatch.call(excel, "Close", new Variant(false));
}
if (ax != null) {
ax.invoke("Quit", new Variant[] {});
ax = null;
}
ComThread.Release();
}
}