一、前言
基于jacob.jar包中com.jacob.activeX.ActiveXComponent打印机驱动控件,实现javax.print.PrintService打印服务,主要应用在excel报表打印队列、自动化打印服务、远程打印、智能打印机等场景,详情代码示例。
二、代码示例
import java.awt.print.PrinterJob;@b@import java.io.File;@b@@b@import javax.print.PrintService;@b@@b@import org.apache.commons.logging.Log;@b@import org.apache.commons.logging.LogFactory;@b@@b@import com.jacob.activeX.ActiveXComponent;@b@ import com.jacob.com.ComThread;@b@ import com.jacob.com.Dispatch;@b@import com.jacob.com.Variant;@b@ @b@@b@public class Printer@b@ {@b@ public static Log log = LogFactory.getLog(Printer.class);@b@ /**@b@ * 打印Excel文件@b@ * @b@ * @param path@b@ * Excel文件路径@b@ * @throws Exception @b@ */@b@ public static void printExcel(String path, String printerName) throws Exception {@b@ System.out.println("打印路径====="+path);@b@ System.out.println("打印机名====="+printerName);@b@ @b@ boolean sign = false;@b@ PrintService[] pss = PrinterJob.lookupPrintServices();@b@ for (PrintService p : pss)@b@ {@b@ if(p.getName().equals(printerName))@b@ {@b@ sign = true;@b@ break;@b@ }@b@ }@b@ @b@ if(!sign)@b@ {@b@ log.error(path+"未找到对应打印机"+printerName);@b@ return ;@b@ }@b@ @b@ ComThread.InitSTA();@b@ ActiveXComponent xl = new ActiveXComponent("Excel.Application");@b@ System.out.println("version=" + xl.getProperty("Version")); @b@ try {@b@ Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();@b@@b@ Dispatch workbook = Dispatch.call(workbooks, "Open", path).toDispatch();@b@@b@ Dispatch.callN(workbook, "PrintOut", new Object[] { Variant.VT_MISSING, Variant.VT_MISSING, new Integer(1),@b@ new Boolean(false), printerName, new Boolean(true), Variant.VT_MISSING, "" });@b@ Dispatch.call(workbook, "Close");@b@ log.info(path+"已成功打印");@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ throw e;@b@ } finally {@b@ // 始终释放资源@b@ xl.invoke("Quit", new Variant[] {});@b@ ComThread.Release();@b@ }@b@ }@b@ @b@ public static void printTest()@b@ {@b@ try@b@ {@b@ ComThread.InitSTA();@b@ ActiveXComponent xl = new ActiveXComponent("Excel.Application"); @b@ System.out.println("version=" + xl.getProperty("Version")); @b@ //new Variant(false) 打印时是否显示文档 false不显示 @b@ Dispatch.put(xl, "Visible", new Variant(true)); @b@ Dispatch workbooks = xl.getProperty("Workbooks").toDispatch(); @b@ @b@ //打开文档 @b@ Dispatch excel=Dispatch.call(workbooks,"Open","D:/报表.xls").toDispatch(); @b@ @b@ Dispatch.get(excel,"PrintOut"); @b@ @b@@b@ }@b@ catch (Exception e)@b@ {@b@ e.printStackTrace();@b@ }finally@b@ { @b@ ComThread.Release();@b@ }@b@ @b@ }@b@ @b@ @b@ public static void main(String[] args)@b@ {@b@ try {@b@ Printer.printExcel("d:\\报表.xls", "C4300-3F-right");@b@ } catch (Exception e) {@b@ // TODO Auto-generated catch block@b@ e.printStackTrace();@b@ }@b@ }@b@ }