1.word转pdf格式
import com.jacob.com.ComThread;
import com.jacob.com.Variant;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
public static int word2Pdf(String fileName,String toFileName){
System.out.println("启动word...");
Long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = null;
try {
app = new ActiveXComponent("word.Application");
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch();
doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[]{
fileName, new Variant(false),new Variant(true) },new int[1]).toDispatch();
System.out.println("打开文档..."+ fileName);
System.out.println("转换文档到PDF..."+ toFileName);
File tofile = new File(toFileName);
if (tofile.exists()){
tofile.delete();
}
Dispatch.invoke(doc,"SaveAs", Dispatch.Method,new Object[]{
toFileName,new Variant(17)},new int[1]);
Long end = System.currentTimeMillis();
System.out.println("转换完成...用时:" + (end - start) + "ms.");
}catch (Exception e){
e.printStackTrace();
System.out.println("=========Error:文档转换失败:" + e.getMessage());
}catch (Throwable t){
t.printStackTrace();
}finally {
Dispatch.call(doc,"Close",false);
System.out.println("关闭文档");
if (app != null){
app.invoke("Quit",new Variant[]{});
}
ComThread.Release();
return 1;
}
}
2.excel转pdf格式
public static void excelToPdf(String inFilePath, String outFilePath){
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)
};
excel = Dispatch.invoke(excels,"Open",Dispatch.Method,obj,new int[9]).toDispatch();
File tofile = new File(outFilePath);
if (tofile.exists()){
tofile.delete();
}
Object[] obj2 = new Object[]{
new Variant(0),
outFilePath,
new Variant(0)
};
Dispatch.invoke(excel, "ExportAsFixedFormat",Dispatch.Method,obj2,new int[1]);
System.out.println("转换完毕!");
}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();
}
}