gpt4 book ai didi

java - 如何用Java检测打印机是否连接到您的计算机?

转载 作者:行者123 更新时间:2023-12-02 02:44:56 25 4
gpt4 key购买 nike

我正在使用 swing Java 创建一个 GUI。我必须使用一键“打印”,它将直接开始打印我设置的文件,而无需打开默认的打印对话框。我必须首先检查打印机是否连接到我的计算机?

最佳答案

可能正在使用PrintServiceLookup

Implementations of this class provide lookup services for print services (typically equivalent to printers) of a particular type.

DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet();
aset.add(MediaSizeName.ISO_A4);
PrintService[] pservices =PrintServiceLookup.lookupPrintServices(flavor, aset);
if (pservices.length > 0) {
DocPrintJob pj = pservices[0].createPrintJob();
//....
}

注意:如果有打印机,PrintService 的数量至少应为一个。如果有实际打印机,则可能至少有 2 个,因为您可以在计算机上安装纯软件打印机。另请参阅this thread .

根据平台和jdk的不同,它可以有some bug ,但除此之外,以下方法应该至少列出打印机:

import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import java.text.*;
import javax.print.attribute.standard.*;

public class ShowPrinters {

public ShowPrinters() {
}

public static void main(String[] args) {
DocFlavor myFormat = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService[] services =PrintServiceLookup.lookupPrintServices(myFormat, aset);
System.out.println("The following printers are available");
for (int i=0;i<services.length;i++) {
System.out.println(" service name: "+services[i].getName());
}
}
}
<小时/>

在此eclipse code source ,您已经看到使用 PrinterState 来检查打印机是否实际连接:

AttributeSet attributes = new HashPrintServiceAttributeSet(
new PrinterName(printerName, Locale.getDefault()));
PrintService[] services = PrintServiceLookup.lookupPrintServices(
DocFlavor.SERVICE_FORMATTED.PRINTABLE,
attributes);
PrintService printService = services[0];
PrintServiceAttributeSet printServiceAttributes = printService.getAttributes();
PrinterState printerState = (PrinterState) printServiceAttributes.get(PrinterState.class);

检查printerState是否不为空。注意:这可能并不总是足够(请参阅 this thread )。

关于java - 如何用Java检测打印机是否连接到您的计算机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1387800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com