9.5. Printing

IT Mill Toolkit does not currently have any special support for printing. Printing on the server-side is anyhow largely independent from the web UI of an application. You just have to take care that the printing does not block server requests, possibly by running printing in another thread.

For client-side printing, most browsers support printing the web page. The print() method in JavaScript opens the print window of the browser. You can easily make a HTML button or link that prints the current page by placing the custom HTML code inside a Label.

main.addComponent(new Label("<input type='button' onClick='print()' value='Click to Print'/>", Label.CONTENT_XHTML));

This button would print the current page. Often you want to be able to print a report or receipt and it should not have any UI components. In such a case you could offer it as a PDF resource, or you could open a new window as is done below and automatically launch printing.

// A button to open the printer-friendly page.
Button printButton = new Button("Click to Print");
main.addComponent(printButton);
printButton.addListener(new Button.ClickListener() {
    public void buttonClick(ClickEvent event) {
        // Create a window that contains stuff you want to print.
        Window printWindow = new Window("Window to Print");
        
        // Have some content to print.
        printWindow.addComponent(new Label("Here's some dynamic content."));
        
        // To execute the print() JavaScript, we need to run it
        // from a custom layout.
        CustomLayout scriptLayout = new CustomLayout("printpage");
        printWindow.addComponent (scriptLayout);
        
        // Add the printing window as an application-level window.
        main.getApplication().addWindow(printWindow);

        // Open the printing window as a new browser window
        main.open(new ExternalResource(printWindow.getURL()), "_new");
    } 
});

How the browser opens the window, as an actual window or just a tab, depends on the browser. Notice that above we create a new window object each time the print button is clicked, which leads to unused window objects. If this is a real problem, you might want to reuse the same window object or clean up the old ones - it's ok because the user doesn't interact with them later anyhow.

You will also need a custom layout that contains the print() JavaScript function that launches the printing. Notice that the custom layout must contain also another element (below a <div>) in addition to the <script> element.

<div>This is some static content.</div>

<script type='text/javascript'>
    print();
</script>

Printing as PDF would not require creating a Window object, but you would need to provide the content as a static or a dynamic resource for the open() method. Printing a PDF file would obviously require a PDF viewer cabability (such as Adobe Reader) in the browser.