用Java强制目标打印机

jtn*_*ire 9 java printing

有没有办法使用HashPrintRequestAttributeSet强制java中的目标打印机?

我不希望用户能够在printdialog中更改打印机

谢谢

Ind*_*bel 11

不得不努力解决这个问题,但对于后代,这里是我的一些代码:

PrintService[] printServices;
PrintService printService;
PageFormat pageFormat;

String printerName = "Your printer name in Devices and Printers";

PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
printServiceAttributeSet.add(new PrinterName(printerName, null));
printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet);

pageFormat = new PageFormat(); // If you want to adjust heigh and width etc. of your paper.
pageFormat = printerjob.defaultPage();

PrinterJob printerjob = PrinterJob.getPrinterJob();

printerjob.setPrintable(new Server(), pageFormat); // Server was my class's name, you use yours.

try {
    printService = printServices[0];
    printerjob.setPrintService(printService); // Try setting the printer you want
} catch (ArrayIndexOutOfBoundsException e) {
    System.err.println("Error: No printer named '" + printerName + "', using default printer.");
    pageFormat = printerjob.defaultPage(); // Set the default printer instead.
} catch (PrinterException exception) {
    System.err.println("Printing error: " + exception);
}

try {
    printerjob.print(); // Actual print command
} catch (PrinterException exception) {
    System.err.println("Printing error: " + exception);
}
Run Code Online (Sandbox Code Playgroud)


小智 6

我的代码解决了这个问题:

String printerNameDesired = "My Printer";

PrintService[] service = PrinterJob.lookupPrintServices(); // list of printers
DocPrintJob docPrintJob = null;

int count = service.length;

for (int i = 0; i < count; i++) {
    if (service[i].getName().equalsIgnoreCase(printerNameDesired)) {
        docPrintJob = service[i].createPrintJob();
        i = count;
    }
}
PrinterJob pjob = PrinterJob.getPrinterJob();
pjob.setPrintService(docPrintJob.getPrintService());
pjob.setJobName("job");
pjob.print();
Run Code Online (Sandbox Code Playgroud)

  • 这个对我有用,只有你忘了初始化docPrintJob.我建议添加以下代码以使其完全正常运行:`DocPrintJob docPrintJob = null;`在`PrintService [] service = PrinterJob.lookupPrintServices();`之后. (2认同)