接口 PrintService 是 DocPrintJob 的工厂。PrintService 描述了打印机的功能,并可查询它来了解打印机支持的属性。


/**


     * 建立与打印机的连接


     * @author Administrator


     *


     */  


public class PrintDemo {  




public static void main(String[] args) {  


JFileChooser fileChooser =new JFileChooser(); //创建文件选择框  


int state = fileChooser.showOpenDialog(null);  //展示文件选择框


if(state == fileChooser.APPROVE_OPTION){  


File file =new File("D:/zkyzl.txt"); //获取选择的文件  


//构建打印机请求属性集  


HashPrintRequestAttributeSet pras =new HashPrintRequestAttributeSet();  


//设置打印格式,因为未确定类型,所以选择autosense  


            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;  


//查找本机所有的可用的打印服务  


            PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);  


//定位默认的打印服务  


            PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();  


//显示打印对话框  


PrintService service = ServiceUI.printDialog(null, 200, 200, printService,   defaultService, flavor, pras);  


if(service != null){  


try {  


DocPrintJob job = service.createPrintJob();//创建打印作业  


FileInputStream fis =new FileInputStream(file); //构造待打印的文件流  (构造流,用来读取用户选择要打印的文件)


DocAttributeSet das =new HashDocAttributeSet();  //可以被打印文档属性集


Doc doc =new SimpleDoc(fis, flavor, das);  //创建可打印文档


                    job.print(doc, pras);  


}catch (Exception e) {  


                    e.printStackTrace();  


                }  


            }  


        }  


    }  


}  


你可能感兴趣的:(接口 PrintService 是 DocPrintJob 的工厂。PrintService 描述了打印机的功能,并可查询它来了解打印机支持的属性。)