如何指定要在Java中使用的打印机?

如何指定要在Java中使用的打印机?,java,printing,Java,Printing,当前正在检索安装在我的计算机上用于打印的默认打印机。我希望能够选择文档要放在哪台打印机上。这样做的最佳方法是什么 代码: PrintService[]服务= PrintServiceLookup.lookupPrintServices(psInFormat,null); System.out.println(“所选打印机”+服务[Printerinx]); //PrintService defaultService=PrintServiceLookup.lookupDefaultPrintSer

当前正在检索安装在我的计算机上用于打印的默认打印机。我希望能够选择文档要放在哪台打印机上。这样做的最佳方法是什么

代码:

PrintService[]服务=
PrintServiceLookup.lookupPrintServices(psInFormat,null);
System.out.println(“所选打印机”+服务[Printerinx]);
//PrintService defaultService=PrintServiceLookup.lookupDefaultPrintService();
DocFlavor[]docFalvor=services[Printerinx].getSupportedDocFlavors();
对于(int i=0;i
创建下面的
PrintUtility
类,导入它并尝试调用
PrintUtility.findPrintService(“我的打印机的名称”)如果您知道打印机名称;如果不知道可以访问哪些打印机,请调用
PrintUtility.getPrinterServiceNameList()用于包含所有可行的注册打印机名称的
列表

有关更多详细信息,请参见:

package com.stackoverflow.print;
导入java.awt.print.PrinterJob;
导入javax.print.PrintService;
导入java.util.List;
导入java.util.ArrayList;
公共最终类打印实用程序{
/**
*检索名称包含指定PrinterName的打印服务;如果未找到,将返回null。
* 
*@返回
*/
公共静态PrintService findPrintService(字符串printerName){
printerName=printerName.toLowerCase();
PrintService=null;
//获取所有打印服务的数组
PrintService[]services=PrinterJob.lookupPrintServices();
//从阵列中检索打印服务
for(int index=0;service==null&&index=0){
服务=服务[索引];
}
}
//返回打印服务
回程服务;
}
/**
*检索打印机服务名称的列表。
* 
*@返回列表
*/
公共静态列表getPrinterServiceNameList(){
//获取所有打印服务的列表
PrintService[]services=PrinterJob.lookupPrintServices();
列表=新的ArrayList();
for(int i=0;i
方法提供了一种按名称查找打印机的方法。使用
PrinterName
属性对象准备一个
HashAttributeSet
,并将其传递给查找方法

使用如下代码:

AttributeSet aset = new HashAttributeSet();
aset.add(new PrinterName("MyPrinter", null));
PrintService[] pservices = 
    PrintServiceLookup.lookupPrintServices(null, aset);
使用CUPS在Linux上工作。

inti;
int i ;

DocFlavor fl= null;

PrintService printService[]= PrintServiceLookup.lookupPrintServices(fl,null); 

for(i=0;i<printService.length;i++)
{
    System.out.println(printService[i]);

}
DOCFL=null; PrintService PrintService[]=PrintServiceLookup.lookupPrintServices(fl,null); 对于(i=0;i
int i ;

DocFlavor fl= null;

PrintService printService[]= PrintServiceLookup.lookupPrintServices(fl,null); 

for(i=0;i<printService.length;i++)
{
    System.out.println(printService[i]);

}