Printing

This guide shows how to work with the Printing API.

Overview

The web page can be printed using one of the following ways:

  1. Using the window.print() JavaScript function. This function can be invoked from the JavaScript code on a web page.
  2. Using the Frame.print() method of the JxBrowser API. The method requests printing of the frame. If you need to print the whole page, you should call the print() method in the main frame. For example:

     browser.mainFrame().ifPresent(Frame::print);
    

The web page is not printed immediately. The PrintCallback will be invoked to tell the browser how to handle the print request. By default all print requests are canceled.

To allow the print request and display the Print Preview dialog use the following code:

browser.set(PrintCallback.class, (params, tell) -> tell.showPrintPreview());

In the Print Preview dialog you can select the preferred printing options:

Print Preview

Configuring Settings

Tell the browser to proceed with printing using the following code:

browser.set(PrintCallback.class, (params, tell) -> tell.print());

After that, either the PrintHtmlCallback or the PrintPdfCallback will be invoked to allow you to configure print settings. These callbacks correspond to the content type that is currently loaded in the browser. For HTML content the PrintHtmlCallback is invoked, and for PDF content the PrintPdfCallback.

Now, let’s see how to work with these callbacks.

Step 1: Choose Printer

First, you need to choose the printer that you want to print on. There are two types of printers: PdfPrinter and SystemPrinter. The PdfPrinter is an equivalent of the Save as PDF option in the Print Preview dialog. The SystemPrinter type represents a printer installed in the system, it can be virtual or physical. The callback params provide a list of the available printers. You can retrieve the PdfPrinter, the default system printer, or choose a printer from the system printers:

browser.set(PrintHtmlCallback.class, (params, tell) -> {
    // The PDF printer is always available.
    PdfPrinter<PdfPrinter.HtmlSettings> pdfPrinter = params.printers().pdfPrinter();

    // The default printer is optional.
    SystemPrinter<SystemPrinter.HtmlSettings> defaultPrinter =
        params.printers()
              .defaultPrinter()
              .orElseThrow(
                  () -> new IllegalStateException("The default printer is not found."));

    // Find a system printer by name.
    SystemPrinter<SystemPrinter.HtmlSettings> systemPrinter =
        params.printers()
              .list()
              .stream()
              .filter(printer -> printer.deviceName()
                                        .equals("Microsoft XPS Document Writer"))
              .findFirst()
              .orElseThrow( () -> new IllegalStateException("The printer is not found."));
});

Step 2: Configure Settings

Each printer is parameterized with a PrintSettings type that defines the print settings available for the printer in the current context. Each printer contains a PrintJob that represents the current printing operation. Print settings are applied to a print job:

SystemPrinter<HtmlSettings> printer = params.printers()
        .defaultPrinter()
        .orElseThrow(IllegalStateException::new);
PrintJob<HtmlSettings> printJob = printer.printJob();
printJob.settings()
        .paperSize(ISO_A4)
        .colorModel(COLOR)
        .enablePrintingBackgrounds()
        .disablePrintingHeaderFooter()
        .orientation(PORTRAIT)
        .apply();

Calling the apply() method will apply the configured settings and regenerate the print preview document that will be later sent to the printer. Before telling the browser to start printing on the printer, you can subscribe to the PrintCompleted event to receive a notification when printing is completed:

printJob.on(PrintCompleted.class, event -> {
    if (event.isSuccess()) {
        System.out.println("Printing is completed successfully.");
    } else {
        System.out.println("Printing has failed.");
    }
});

Step 3: Start Printing

Now we’re ready to start printing:

tell.proceed(printer);

Here is the complete code snippet:

browser.set(PrintHtmlCallback.class, (params, tell) -> {
    SystemPrinter<HtmlSettings> printer = params.printers()
            .defaultPrinter()
            .orElseThrow(IllegalStateException::new);
    PrintJob<HtmlSettings> printJob = printer.printJob();
    printJob.settings()
            .paperSize(ISO_A4)
            .colorModel(COLOR)
            .enablePrintingBackgrounds()
            .disablePrintingHeaderFooter()
            .orientation(PORTRAIT)
            .apply();
    printJob.on(PrintCompleted.class, event -> {
        if (event.isSuccess()) {
            System.out.println("Printing is completed successfully.");
        } else {
            System.out.println("Printing has failed.");
        }
    });
    tell.proceed(printer);
});

Printing on the PdfPrinter is just the same, except you must specify the destination PDF file path:

browser.set(PrintHtmlCallback.class, (params, tell) -> {
    PdfPrinter<HtmlSettings> printer = params.printers().pdfPrinter();
    PrintJob<HtmlSettings> printJob = printer.printJob();
    printJob.settings()
            .paperSize(ISO_A4)
            .enablePrintingBackgrounds()
            .pdfFilePath(Paths.get("<path-to-pdf-file>"))
            .apply();
    printJob.on(PrintCompleted.class, event -> {
        if (event.isSuccess()) {
            System.out.println("Printing is completed successfully.");
        } else {
            System.out.println("Printing has failed.");
        }
    });
    tell.proceed(printer);
});

The PrintPdfCallback has the same interface, and the only difference is in the print settings that can be applied to a print job.

Canceling Printing

To cancel printing, use the following approach:

browser.set(PrintCallback.class, (params, tell) -> tell.cancel());
Go Top