352 Print to Printer

Print to Printer

Two ways to reach a printer: from the browser (the user's own print dialog and printer) or from the server with the Java Print Service - no dialog, the server picks the printer, copies and duplex. Server printing uses the printers installed on this PC.

Server print job

 

With "print to file" the printer driver writes its output to data/printed. For Microsoft Print to PDF that file is a PDF you can open below.

Browser print

The PDF on the right is shown by the browser's PDF viewer. Its print button opens your own print dialog - the server is not involved.

Printers on this PC

PrintServiceLookup.lookupPrintServices()
NameTypeStatusQueued jobs
Microsoft Print to PDF default Virtual (file / app) Accepting jobs 0

Document

How it works
  • PrintServiceLookup.lookupPrintServices(null, null) lists the installed printers (Windows spooler).
  • PDFBox PDFPageable renders each PDF page; PrinterJob.print(attributes) prints without a dialog.
  • Attributes: Copies, Sides.TWO_SIDED_LONG_EDGE (duplex), JobName and Destination(file URI) for print-to-file.
  • Server printing only reaches printers of the machine running Spring Boot. Users far away print from their browser.
try (PDDocument pdf = Loader.loadPDF(bytes)) {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintService(service);
    job.setPageable(new PDFPageable(pdf));
    PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();
    attrs.add(new Copies(2));
    attrs.add(Sides.TWO_SIDED_LONG_EDGE);
    job.print(attrs);
}

Files: service/PrinterService.java, web/PrinterController.java.