Java print Service API and a non default printer

679 views Asked by At

So i have an application that sends tasks to a printer. Everything is working fine if the printer i'm sending tasks to is set to "default printer", the moment i change the default printer and try sending tasks again to this same printer which is already not the default one i get the following picture: through java it finds the correct printer, sends a task and in the printing queue the statuses change as follows - Spooling, printing and sent to Printer. After a few seconds sent to Printer status disappears and nothing happens, no errors, nothing. Watching my code i can't really see any problems. It finds everything correctly and i'm not really sure where to look for a solution and which code snippet to provide here in order to make the picture more clear.

It certainly gets through this point correctly:

private void sendDataToPrinter(PrinterContent printerContent) {
    //Get available printers
    PrintService[] printServices = Constants.PRINT_SERVICES;

    //Look for right printer and print data
    for (int i = 0;  i < printServices.length; i++) {

        if (printServices[i].getName().equals(printerContent.getPrinterName())) {
            print(printServices[i], printerContent);
            break;
        }
    }
}

This is the print method:

private void print(PrintService printer, PrinterContent printerContent) {

    Document htmlDocument = ConverterUtil.convertStringToHtmlDocument(printerContent.getPrintContent());
    PDDocument pdfDocument = ConverterUtil.convertHtmlToPdf(htmlDocument);
    PrinterJob printJob = createPDFPrinterJob(pdfDocument);

    try {
        printJob.setPrintService(printer);
        printJob.print();
    }
    catch(PrinterException ex) {
        ex.printStackTrace();
    }
}

And the createPDFPrinterJob method:

private PrinterJob createPDFPrinterJob(PDDocument pdfDocument) {

    PrinterJob printJob = PrinterJob.getPrinterJob();

    PageFormat pageFormat = printJob.defaultPage();
    pageFormat.setOrientation(PageFormat.PORTRAIT);

    pageFormat.setPaper(PrinterJob.getPrinterJob().defaultPage().getPaper());

    try {
        printJob.setPrintable(new PDPageable(pdfDocument), pageFormat);
    }
    catch(PrinterException ex) {
        ex.printStackTrace();
    }

    return printJob;
}
0

There are 0 answers