How to Print Text

The JTextComponent class provides support for printing text documents. The JTextComponent API includes methods that allow you to implement both basic and advanced printing tasks. Supported formats include HTML, RTF, and plain text. For common printing tasks such as simply printing a text document, use the print method directly. The print method has several forms with various argument sets. This method prepares your text document, gets a corresponding Printable object, and sends it to a printer.

If the default implementation of the Printable object does not meet your needs, you can customize the printing layout by overriding the getPrintable method to wrap the default Printable or even replace it altogether.

The easiest way to print your text component is to call the print method without parameters. See the code example below.

try {
    boolean complete = textComponent.print();
    if (complete) {
        /* show a success message  */
        ...
    } else {
        /*show a message indicating that printing was cancelled */
        ...
    }
} catch (PrinterException pe) {
    /* Printing failed, report to the user */
    ...
}

When you call the print method with no parameters, a print dialog is displayed, and then your text component is printed interactively without a header or a footer. The code example below shows the print method signature with the complete set of arguments.

boolean complete = textComponent.print(MessageFormat headerFormat,
                                       MessageFormat footerFormat, 
                                       boolean showPrintDialog,
                                       PrintService service
                                       PrintRequestAttributeSet attributes,
                                       boolean interactive);

When you call the print method with all arguments, you explicitly choose printing features such as header and footer text, printing attributes, a destination print service, and also whether to show a print dialog or not, and whether to print interactively or non-interactively. To decide which parameters suit your needs best, see the description of available features below.

The JTextComponent printing API provides the following features:

Printing Interactively or Non-interactively

In interactive mode a progress dialog with an abort option is shown for the duration of printing. Here is a sample of a progress dialog.

A screenshot of a printing progress dialog

This dialog allows the user to keep track of printing progress. The progress dialog is modal when the print method is called on the event dispatch thread and non-modal otherwise. It is important that your document remain unchanged while being printed, otherwise the printing behavior is undefined. The print method ensures that your document will not be changed and disables the component for the duration of printing.

If you call the print method on the event dispatch thread in non-interactive mode, then all events including repaints will be blocked. That is why printing non-interactively on EDT is only recommended for applications with non-visible GUI.

You can display a standard print dialog which allows the user to do the following:

  • Select a printer

  • Specify number of copies

  • Change printing attributes

  • Cancel printing before it has been started

  • Start printing

A screenshot of a printing dialog

You may notice that the print dialog does not specify the total number of pages in the printout. This is because the text printing implementation uses the Printable API and the total number of pages is not known before printing time.

Headers and footers are provided by MessageFormat parameters. These parameters allow the header and footer to be localized. Read the documentation for the MessageFormat class as characters such as single quotes are special and need to be avoided. Both headers and footers are centered. You can insert a page number by using {0} .

MessageFormat footer = new MessageFormat("Page - {0}");

Since the total number of pages in the output is not known before printing time, there is no way to specify a numbering format like "Page 1 of 5".

Automatic Layout and Pagination

With the use of the JTextComponent printing API you do not need to take care of layout and pagination. Both layout and pagination are done automatically. The document content is formatted to fit the page size and spreads across multiple pages. You only need to specify an appropriate footer text format to the print method if you want to insert a page number in the footer. As demonstrated earlier, you can specify the page number in your footer by including "{0}" in the string given to the MessageFormat footer parameter. In the printed output, {0} will be replaced by the current page number.

Text Area Printing Example

Let us look at an example called TextAreaPrintingDemo. The main feature of this demo is printing a text document either on the event dispatch thread or on a background thread depending on the user's choice. This demo displays a text area, allows to select several printing features, and prints the text area's content according to the selected options. The entire code for this program can be found inTextAreaPrintingDemo.java. This demo's rich GUI is built in the NetBeans IDE GUI builder. Here is a picture of the TextAreaPrintingDemo application.

A screenshot of TextAreaPrintingDemo

Note

boolean print()
boolean print(MessageFormat, MessageFormat)
boolean print(MessageFormat, MessageFormat, boolean, PrintRequestAttributeSet, boolean, PrintService) When called without arguments, displays a print dialog, and then prints this text component interactively without a header or a footer text. Returns true if the user continued printing and false if the user cancelled printing.
When called with the two MessageFormat arguments, displays a print dialog, and then prints this text component interactively with the specified header and footer text.
When called with a full set of arguments, prints this text component according to the specified arguments. The two MessageFormat arguments specify header and footer text. The first boolean argument defines whether to show a print dialog or not. Another boolean argument specifies whether to print interactively or not. With two other arguments you can specify printing attributes and a print service.
Whenever a PrintService argument is omitted, the default printer will be used.


About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Previous page: How to Print Tables
Next page: How to Create a Splash Screen