Force target printer in Java

13,859

My code to solve this :

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();
Share:
13,859
jtnire
Author by

jtnire

Updated on July 24, 2022

Comments

  • jtnire
    jtnire almost 2 years

    Is there a way to force the target printer in java, using HashPrintRequestAttributeSet ?

    I don't want the user to be able to change the printer in the printdialog

    Thanks

  • bashoogzaad
    bashoogzaad over 9 years
    This one worked for me, only you forgot to initialize the docPrintJob. I suggest to add the following code to make it fully functional: DocPrintJob docPrintJob = null; after PrintService[] service = PrinterJob.lookupPrintServices();.