List icon Contents

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:

    Java
    Kotlin
    browser.mainFrame().ifPresent(Frame::print);
    
    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.

Print preview

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

Java
Kotlin
browser.set(PrintCallback.class, (params, tell) -> tell.showPrintPreview());
browser.set(PrintCallback::class.java, PrintCallback { 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:

Java
Kotlin
browser.set(PrintCallback.class, (params, tell) -> tell.print());
browser.set(PrintCallback::class.java, PrintCallback { 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 a 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:

Java
Kotlin
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."));
});
browser.set(PrintHtmlCallback::class.java, PrintHtmlCallback { params, tell ->
    // The PDF printer is always available.
    val pdfPrinter = params.printers().pdfPrinter()

    // The default printer is optional.
    val defaultPrinter = params.printers()
        .defaultPrinter()
        .orElseThrow { IllegalStateException("The default printer is not found.") }

    // Find a system printer by name.
    val systemPrinter = params.printers()
        .list()
        .firstOrNull { it.deviceName() == "Microsoft XPS Document Writer" }
        ?: throw 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:

Java
Kotlin
SystemPrinter<SystemPrinter.HtmlSettings> printer = params.printers()
        .defaultPrinter()
        .orElseThrow(IllegalStateException::new);
PrintJob<SystemPrinter.HtmlSettings> printJob = printer.printJob();
printJob.settings()
        .header("<span style='font-size: 12px;'>Page header:</span>"
                + "<span class='title'></span>")
        .footer("<span style='font-size: 12px;'>Page footer:</span>"
                + "<span class='pageNumber'></span>")
        .paperSize(ISO_A4)
        .colorModel(COLOR)
        .enablePrintingBackgrounds()
        .disablePrintingHeaderFooter()
        .orientation(PORTRAIT)
        .apply();
val printer = params.printers()
    .defaultPrinter()
    .orElseThrow { IllegalStateException() }
val printJob = printer.printJob()
printJob.settings()
    .header(
        "<span style='font-size: 12px;'>Page header:</span>"
                + "<span class='title'></span>"
    )
    .footer(
        "<span style='font-size: 12px;'>Page footer:</span>"
                + "<span class='pageNumber'></span>"
    )
    .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:

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

Step 3: Start printing

Now we’re ready to start printing:

Java
Kotlin
tell.proceed(printer);
tell.proceed(printer)

Here is the complete code snippet:

Java
Kotlin
browser.set(PrintHtmlCallback.class, (params, tell) -> {
    SystemPrinter<SystemPrinter.HtmlSettings> printer = params.printers()
            .defaultPrinter()
            .orElseThrow(IllegalStateException::new);
    PrintJob<SystemPrinter.HtmlSettings> printJob = printer.printJob();
    printJob.settings()
            .header("<span style='font-size: 12px;'>Page header:</span>"
                    + "<span class='title'></span>")
            .footer("<span style='font-size: 12px;'>Page footer:</span>"
                    + "<span class='pageNumber'></span>")
            .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);
});
browser.set(PrintHtmlCallback::class.java, PrintHtmlCallback { params, tell ->
    val printer = params.printers()
        .defaultPrinter()
        .orElseThrow { IllegalStateException() }
    val printJob = printer.printJob()
    printJob.settings()
        .header("<span style='font-size: 12px;'>Page header:</span>"
                + "<span class='title'></span>")
        .footer("<span style='font-size: 12px;'>Page footer:</span>"
                + "<span class='pageNumber'></span>")
        .paperSize(ISO_A4)
        .colorModel(COLOR)
        .enablePrintingBackgrounds()
        .disablePrintingHeaderFooter()
        .orientation(PORTRAIT)
        .apply()
    printJob.on(PrintCompleted::class.java) { event ->
        if (event.isSuccess()) {
            println("Printing is completed successfully.")
        } else {
            println("Printing has failed.")
        }
    }
    tell.proceed(printer)
})

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

Java
Kotlin
browser.set(PrintHtmlCallback.class, (params, tell) -> {
    PdfPrinter<PdfPrinter.HtmlSettings> printer = params.printers().pdfPrinter();
    PrintJob<PdfPrinter.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);
});
browser.set(PrintHtmlCallback::class.java, PrintHtmlCallback { params, tell ->
    val printer = params.printers().pdfPrinter()
    val printJob = printer.printJob()
    printJob.settings()
        .paperSize(ISO_A4)
        .enablePrintingBackgrounds()
        .pdfFilePath(Path("<path-to-pdf-file>"))
        .apply()
    printJob.on(PrintCompleted::class.java) { event ->
        if (event.isSuccess()) {
            println("Printing is completed successfully.")
        } else {
            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:

Java
Kotlin
browser.set(PrintCallback.class, (params, tell) -> tell.cancel());
browser.set(PrintCallback::class.java, PrintCallback { params, tell -> tell.cancel() })