Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listener for java.awt.print.PrinterJob

Tags:

java

printing

awt

Is a listener available for java.awt.print.PrinterJob? I could only find PrintJobListener in javax.print.DocPrintJob. I am looking for its equivalent in java.awt.print.PrinterJob, so that I could track if there are issues in printing.

like image 372
Rachel Avatar asked Oct 14 '22 21:10

Rachel


1 Answers

This gonna be like necroing an old question but to those who are searching for an answer like me, I hope it will help.

It is only possible to use events for java.awt stuff by converting your printable to the javax.print. Here is how you can do it properly without breaking the pageFormat.

    // get default service
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    // this is your old awt job, which you can use to get default pageFormat
    PrinterJob job = PrinterJob.getPrinterJob();
    // set your printer service to old awt so that you can get the default paper
    job.setPrintService(service);
    // get the default page format from the printer you selected
    PageFormat pageFormat = job.getPageFormat(null);
    // do some paper stuff etc. here
    // get your doc
    DocPrintJob printJob = service.createPrintJob();
    Book book = new Book();
    // Print interface implements printable
    book.append(new PrintInterface(), pageFormat);
    // make your attr here
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(PrintQuality.HIGH);
    // Create your doc for pageable
    SimpleDoc doc = new SimpleDoc(book, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
    /// and voila, print it
    printJob.print(doc, aset);

The same can be done for a single printable but currently I couldn't find a way to change PageFormat for that, so I just skipped it. This way you can use Pageable or Printable and you can still use those events by simply adding them with printJob.addPrintJobListener()

This is not a full code by any means but it gives you the idea if you are in for it.

like image 134
bmlkc Avatar answered Nov 02 '22 09:11

bmlkc