最近做项目需要打印office,搞了好久,现在分享下。打印word和excel是可以根据参数设置打印机的,但是ppt的ActivePrinter属性是只读的,不能设置打印机,看了ppt只能转换为PDF再打印了
private static void printWord(PrintService printService, byte[] content, String type, PageRanges pageRanges){
//得到文件路径String filePath = getPrintUtils().writeTemporaryFile(content, type);
ActiveXComponent app = null; //word运行程序对象
Dispatch doc = null; //word文档
try{
ComThread.InitSTA();
//创建ActiveX部件对象
app = new ActiveXComponent("Word.Application");
//设置打印机名称
app.setProperty("ActivePrinter", new Variant(printService.getName()));
Dispatch.put(app, "Visible", new Variant(false));
//打开word文档
Dispatch docs = app.getProperty("Documents").toDispatch();
doc = Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[]{filePath, new Variant(false), new Variant(true), new Variant(false)},
new int[1]).toDispatch();
//开始打印
Object[] object = new Object[2];
object[0] = Variant.VT_MISSING;
object[1] = Variant.VT_MISSING;
if(pageRanges != null) {
object[0] = new Integer(pageRanges.getMembers()[0][0]);
object[1] = new Integer(pageRanges.getMembers()[0][1]);
}
//object对象具体参数可参考MSDN上word的Document方法设置参数
}catch (Exception e){
e.printStackTrace();
return;
}finally {
if(doc != null){
Dispatch.call(doc, "Close", false);
}
if(app != null){
app.invoke("Quit", 0);
}
ComThread.Release();
//删除临时文件
File file = new File(filePath);
file.delete();
}
}
private static void printExcel(PrintService printService, byte[] content, String type, PageRanges pageRanges){
String filePath = getPrintUtils().writeTemporaryFile(content, type);
ActiveXComponent app = null; //word运行程序对象
Dispatch excel = null; //Excel文档
try {
ComThread.InitSTA();
app = new ActiveXComponent("Excel.Application");
// 打开文档
Dispatch.put(app, "Visible", new Variant(false));
Dispatch workbooks = app.getProperty("Workbooks").toDispatch();
excel = Dispatch.call(workbooks, "Open", filePath).toDispatch();
//开始打印
Object[] object = new Object[8];
object[0] = Variant.VT_MISSING;
object[1] = Variant.VT_MISSING;
if(pageRanges != null){
object[0] = new Integer(pageRanges.getMembers()[0][0]);
object[1] = new Integer(pageRanges.getMembers()[0][1]);
}
object[2] = Variant.VT_MISSING;
object[3] = new Boolean(false);
object[4] = printService.getName();
object[5] = new Boolean(false);
object[6] = Variant.VT_MISSING;
object[7] = Variant.VT_MISSING;
//object对象具体参数可参考MSDN上excel的Workbook方法设置参数
Dispatch.callN(excel,"PrintOut",object);
}catch (Exception e){
e.printStackTrace();
}finally {
if(excel != null){
Dispatch.call(excel, "Close", false);
}
if(app != null){
app.invoke("Quit", new Variant[] {});
}
ComThread.Release();
//删除临时文件
File file = new File(filePath);
file.delete();
}
}