java - 如何使用Java在网络打印机上打印?

标签 java printing

使用 Java,我需要在本地未安装的网络打印机上进行打印。我只知道打印机名称。我见过的所有教程都以类似以下内容开头:

PrintService []services = PrinterJob.lookupPrintServices();

问题是不能安装打印机,所以在那种情况下服务将是空的。我需要直接设置打印机名称,而不仅仅是通过可见打印机进行枚举。

最佳答案

如果打印机未注册到运行打印应用程序的 Windows/Active Directory 用户,则 Java AWT 打印将无法通过路径找到打印机。您必须通过 Windows“设备和打印机”将打印机路径注册为该用户的打印机,才能使其可见。然后,作为该用户,您必须运行 lookupPrintServices 以查看可用打印机列表,并通过列出的确切名称 String 检索正确的 PrintService

/**
 * Retrieve the specified Print Service; will return null if not found.
 * @return
 */
public static PrintService findPrintService(String printerName) {

    PrintService service = null;
    
    // Get array of all print services - sort order NOT GUARANTEED!
    PrintService[] services = PrinterJob.lookupPrintServices();
    
    // Retrieve specified print service from the array
    for (int index = 0; service == null && index < services.length; index++) {
        
        if (services[index].getName().equalsIgnoreCase(printerName)) {

            service = services[index];
        }
    }

    // Return the print service
    return service;
}

/**
 * Retrieve a PrinterJob instance set with the PrinterService using the printerName.
 * 
 * @return
 * @throws Exception IllegalStateException if expected printer is not found.
 */
public static PrinterJob findPrinterJob(String printerName) throws Exception {

    // Retrieve the Printer Service
    PrintService printService = PrintUtility.findPrintService(printerName);

    // Validate the Printer Service
    if (printService == null) {

        throw new IllegalStateException("Unrecognized Printer Service \"" + printerName + '"');
    }
    
    // Obtain a Printer Job instance.
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    
    // Set the Print Service.
    printerJob.setPrintService(printService);

    // Return Print Job
    return printerJob;
}

/**
 * Printer list does not necessarily refresh if you change the list of 
 * printers within the O/S; you can run this to refresh if necessary.
 */
public static void refreshSystemPrinterList() {

    Class[] classes = PrintServiceLookup.class.getDeclaredClasses();

    for (int i = 0; i < classes.length; i++) {

        if ("javax.print.PrintServiceLookup$Services".equals(classes[i].getName())) {

            sun.awt.AppContext.getAppContext().remove(classes[i]);
            break;
        }
    }
}

关于java - 如何使用Java在网络打印机上打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11230502/

相关文章:

c# - 如何在打印 PDF 时设置打印机设置

java - JPA Criteria 查询分组依据并获取最后一条记录

java - 无法加载方言 'org.drools.compiler.rule.builder.dialect.java.JavaDialectConfiguration:java:null'

c++ - 从 std::vector 打印逗号分隔列表

java - 无法使用打印机打印标签

python - 在 python 3 str.format 中抑制打印换行符

css - 用于非打印用户代理的分页打印的 HTML 和 CSS

java - 将 Timescale DB 的 Gapfill 与 JOOQ 一起使用会抛出参数 : start cannot be NULL

Java:如何在开关之外更改变量的值? (刚刚读完帖子)

java - 仅调整 Java Swing 组件一部分的大小