logo
  J2Printer
logo

[Basic printing ] [Multiple Pageables and Books ] [Printing properties ] [Pageable properties ]
[Print, Page Setup, and Print Preview dialogs[Print to Image, HTML, PDF ] [Additional capabilities ]

also see: [J2Printer14 ] [J2PrinterWebStart ]


Basic printing

J2PrinterWorks provides the base class J2Printer for managing the Java printing process.  J2Printer implements the complete process for printing a Java Pageable.  Pageable is the Java interface for a set of printable pages.  The J2Printer class supports such features as headers, footers, and margins, display of page setup, print preview, and print dialogs, printing in a background thread, and detecting print progress events.

J2PrinterWorks provides 7 classes for creating Pageables (each described in their own sections): J2TextPrinter (for JTextPane, JEditorPane, and JTextArea), J2TablePrinter (for JTable), J2TreePrinter (for JTree), J2ListPrinter (for JList), J2PanelPrinter (for JPanel), J2ComponentPrinter (for any Java Component), and J2FlowPrinter (for a sequence of Flowables).  For example, the following code creates a Pageable instance for a JTextPane:

    J2TextPrinter yourPageable = new J2TextPrinter(yourJTextPane);

You may also create your own Pageables by implementing the Java Pageable interface yourself.

Having created yourPageable, printing it with J2PrinterWorks is accomplished by instantiating a J2Printer instance, giving it your Pageable, and telling it to print, i.e.:

    J2Printer printer = new J2Printer();
    printer.setPageable(yourPageable);
    printer.print();

The J2Printer print method also takes Pageable as an argument, so shorthand alternatives are possible such as:
    new J2Printer().print(yourPageable);
or even:
    new J2Printer().print(new J2TextPrinter(yourJTextPane));

 

Multiple Pageables and Books

J2Printer can also print a series of Pageables as a single document using an addPageable method:

        J2Printer printer = new J2Printer();
        printer.setPageable(pageable1);
        printer.addPageable(pageable2);
        printer.addPageable(pageable3);
        printer.print();

This sequence groups three Pageables together in a single Pageable, implemented using the Java class Book.  The result is that the individual pages from the three Pageables will be printed back-to-back in one document.

Having used setPageable and/or addPageable to specify some Pageables, you can use clearPageable() to reset to an empty overall document.  Also, note that since the J2Printer instance starts with an empty overall document, you could have used a addPageable in place of the the first setPageable call above.
 

Printing properties

J2Printer contains a number of methods for controlling the printing process itself.  Some of the more commonly used are these:

cancelPrinting ()
          Cancel the current printing job

setNumberOfCopies (int numberOfCopies)
          Sets number of copies to be printed.

setPaperSize (double paperW, double paperH)
          Sets the paper width and height when paper viewed in PORTRAIT.

setPrintDialogUsed (boolean printDialogUsed)
          Sets whether to show a print dialog before printing.

setPrintJobName (String printJobName)
          Sets the print job name that appears in the system print monitor.

setSeparatePrintThread (boolean separatePrintThread)
          Sets whether to print from a separate thread (instead of from the thread that called the print method).

Pageable properties

J2Printer also has methods for setting the headers, footers, margins, orientation, and scale for the Pageable that it will print.  The J2Printer values for these define the "global" (default) values used for the overall document, which will be used unless an individual Pageable specifies its own "local" values (see "Global vs. local values" section below).

The following sections describe the individual methods used to control these features.
 

Headers and footers, boxes and lines

These methods let you define left, center, and right headers and footers.  Any of these can be a String specifying a single line in a single font, or a JLabel specifying multiple lines, rich text, and Images. Any of these can contain page numbering and date and time formatting (see Javadoc descriptions for the header and footer methods).  Headers and footers can be different on the first page vs. the rest of the pages.  Headers and/or footers areas can also be surrounded by a box, separated from the body by a line, or neither of these.

If you wish to have no headers (and/or no footers) and have the body of your document use this space, set the left, center, and right headers (and/or footers) to each be the empty String ("").  In this case, J2PrinterWorks will automatically omit drawing the headers (and/or footers), the box or line surrounding them, and the gap separating them from the body, and instead use this extra space for the body of the document.

NOTE: In the current version of J2PrinterWorks, there is nothing to prevent using too long Strings or JLabels in your headers or footers and as a consequence having them overlap or extend beyond the specified margins or outside the boxes and lines.

The main header and footer methods are:

setLeftHeader (java.lang.Object leftHeader)
          Sets the left header using either a String or JLabel.  There are similar methods for setCenterHeader and setRightHeader, as well as for setLeftFooter , setCenterFooter, and setRightFooter .

setHeaderStyle (int style)
          Sets header style (BOX, LINE, or NONE).  There is a similar method for setFooterStyle .

setHeaderFont (java.awt.Font font)
          Sets the font for printing the headers when these are specified using a String.  There is a similar method for setFooterFont .

setGapAboveFooter (double gapAboveFooter)
          Sets the gap between the bottom of the last line of body and the top of the footer in inches.  There is a similar method for setGapBelowHeader .

Any of the above methods can be specified with an additional argument to separately control whether the settings apply to the first page vs. the remaining pages, for example:

setLeftHeader (int which, java.lang.Object leftHeader)
          Sets the left footer for either page 1 (FIRST) or pages 2...n (REST) using a String or JLabel.
 

Margins

You can control the top, bottom, left, and right margins of your document.  These are specified from the edge of the page, but since most printers have an "unprintable margin" area, the actual margin used will not be less than the unprintable margin.

setTopMargin (double topMargin)
          Sets the top margin (above header) in inches from the edge of the page.  There are similar methods for setBottomMargin, setLeftMargin , and setRightMargin .
 

Orientation and scale

You can control the printing orientation on the page using the following method:

setOrientation (int orientation)
          Sets page orientation (portrait vs. landscape vs. reverse landscape).

You can control the scale with which pages are printed by calling the method:

setScale (double scale)
          Sets magnification or minification scaling factor.

Setting the value of scale to 1.0 results in unscaled (100%) printing.  Setting this value to greater than 1.0 or less than 1.0 will cause magnification or minification, respectively.
 

Reading and writing PageFormat instances

J2Printer prints using margin, paper size, and orientation values set using the above methods.  As a convenience for developers who need a standard Java PageFormat instance with the equivalent margins, paper size, and orientation, we have provided methods to convert between J2Printer's values and PageFormat.  These can be particularly useful when working with externally-defined Pageables.  The methods are:

getPageFormat ()
          Method for creating a PageFormat instance based on the J2Printer margins, paper size, & orientation.

setPageFormat (java.awt.print.PageFormat pageFormat)
          Method for setting the J2Printer margins, paper size, & orientation based on the specified PageFormat.
 

Global vs. local values

Each of the individual J2PrinterWorks Pageable components such as J2TextPrinter has a parallel set of methods for setting the headers, footers, margins, orientation, and scale.  The J2Printer methods set the global (overall, default) values for these properties, which are the values that will be used unless a given Pageable sets it own local value.  For example:

    J2Printer printer = new J2Printer();
    printer.setLeftFooter("Overall footer"); // set global properties
    J2TextPrinter textPrinter = new J2TextPrinter(yourJTextPane);
    J2TablePrinter tablePrinter = new J2TextPrinter(yourJTable);
    textPrinter.setLeftFooter("My footer");  // set properties for this Pageable
    printer.addPageable(textPrinter);
    printer.addPageable(tablePrinter);
    printer.print();

In this case, "My footer" will be the value used on the textPrinter pages, whereas "Overall footer" will be the value used on the tablePrinter pages (and any other Pageables in the document that do not specify their own values).
 

Print, Page Setup, and Print Preview dialogs


Print dialog

By default, the native OS print dialog is displayed when the J2Printer method print() is called, which allows the user to control printer selection, page range, number of copies, etc.  On Windows, the native print dialog typically looks like the following:

native print

If the J2Printer method setPrintDialogUsed(false) has been called, then no print dialog is shown when the print() method is called and instead J2PrinterWorks prints one copy of all pages on the default printer.


Page Setup dialog

The native OS page setup dialog can be invoked by J2Printer.  The current "global" margins, orientation, and paper size will be reflected in this dialog and any changes made by the user will be used to update the corresponding J2Printer properties.  To display the page setup dialog, call the following method:

showPageSetupDialog ()
          Method for showing the standard Page Setup dialog.

On Windows, the native page setup dialog typically looks like the following:

native page setup



Print preview dialog

J2PrinterWorks also provides its own print preview dialog which can display a preview of the document to be printed.  The print preview images are rendered by the exact same code that will be used to print.  On Windows, the standard J2PrinterWorks print preview dialog looks as follows:

print preview

The J2PrinterWorks print preview dialog supports buttons for first page, last page, next page, and previous page, or the user can type in any page number directly.  The print preview dialog can display the page images at any scale and supports buttons for zoom in and zoom out operations as well as allowing the user to type in any desired scale factor.  The print preview dialog also can switch between one page and two page (side-by-side) display mode.  To bring up the print preview dialog, call the following method:

showPrintPreviewDialog (java.awt.Component parent)
          Method for showing a Print Preview dialog.


Initial page number, zoom factor, one vs. two page

To control the initial page number, zoom factor, and one vs. two page setting, the following methods are available:

setPrintPreviewPageNumber(int pageNumber)
          Sets the starting page number displayed in the print preview dialog.

setPrintPreviewScale(double printPreviewScale)
          Sets the starting magnification/minification scale of the print preview dialog.

setPrintPreviewTwoPageDisplay(boolean twoPageDisplay)
          Specifies whether print preview dialog starts in one or two page display mode.


Print Preview Page Setup button

To control the page setup dialog to be used when the "Page Setup" button is pressed in the print preview dialog, or to omit this button from the print preview dialog, use the following methods:

setPrintPreviewPageSetupDialog(java.awt.Dialog dialog)
          Sets the page setup dialog to display when user hits "Page Setup" button in print preview dialog.

showPrintPreviewPageSetupButton(boolean showPageSetupButton)
          Method to specify whether to include Page Setup button in Print Preview dialog (default: true.  Deprecated, use customizable Print Preview toolbar mechanism, see below).


Color vs. monochrome

To control whether the print preview dialog displays its page images in color or monochrome, the following method is available:

setPageImagesMonochrome(boolean monochrome)
          Method used in conjunction with the getPageImage methods, and thereby the print preview dialog page images, specifying whether the images are monochrome (gray scale) instead of color (default: false = color).


Print preview dialog status after hitting "Print"

To control what happens to the Print Preview dialog when the user clicks on the "Print" button in the Print Preview dialog, the following method is available:

setPrintPreviewCloseOnPrint(int closeOnPrint)
          Specifies whether and when the print preview dialog will close when user hits "Print" button (possible values are BEFORE, WAIT, and NEVER)


Customizable Print Preview toolbar

The J2PrinterWorks Print Preview dialog uses a Java JToolPrinter for its control buttons.  You can obtain a reference to this JToolBar using the following method:

 getPrintPreviewToolBar()
          Method for gaining access to the print preview dialog toolbar.

Using this JToolBar reference, you can gain access to all the buttons and other components displayed within the JToolBar by the Print Preview dialog.  This enables you to perform substantial customization of the Print Preview dialog toolbar, including: 1) adding, omitting, or changing button text, 2) adding, omitting, or changing button icons, 3) modifying fonts, colors, sizes, spacing, borders, look and feel. tool tips, floatable and rollover properties, etc, 4) omitting or rearranging buttons and other elements, 5) adding your own buttons and other elements to the toolbar which can control the print preview dialog, etc.  The exact order of the Components that appear within the default Print Preview JToolBar is as follows:

Component
Type
Description
0
JButton
Print
1
JSeparator

2
JButton
Page Setup
3
JSeparator

4
JButton
First Page
5
JButton
Previous Page
6
JLabel
"Page"
7
JTextField
current page number
8
JLabel
" of "
9
JLabel
total number of pages
10
JButton
Next Page
11
JButton
Lsst Page
12
JSeparator

13
JButton
Zoom Out
14
JTextField
scale factor
15
JButton
Zoom In
16
JSeparator

17
JButton
One Page Display
18
JButton
Two Page Display
19
JSeparator

20
JButton
Close

For example, using this information, the following code will remove the text ("Print") from the Print button, remove the icon from the Page Setup button, hide the Close button (which is redundant with the Print Preview dialog "close" box) as well as its preceeding Separator, and swap the order of the Zoom In and Zoom Out buttons:

        JToolBar jtb = printer.getPrintPreviewToolBar();
        Component[] comps = jtb.getComponents();
   
        JButton printButton = (JButton)comps[0];
        printButton.setText(""); // remove text from Print button
   
        JButton setupButton = (JButton)comps[2];
        setupButton.setIcon(null); // remove icon from Page Setup button
   
        comps[20].setVisible(false); // hide the Close button
        comps[19].setVisible(false); // hide the Separator before the Close button
   
        jtb.removeAll(); // remove all toolbar components
        for (int i=0; i<13; i++) jtb.add(comps[i]); // add back the first 13 components
        jtb.add(comps[15]); // add back the Zoom Out button
        jtb.add(comps[14]); // add back the scale factor JTextField
        jtb.add(comps[13]); // add back the Zoom In button       
        for (int i=16; i<21; i++) jtb.add(comps[i]); // add back remaining components

Also, note that you can add your own components that evoke the pre-defined actions of the existing buttons and text fields.  For example, the following code will add a button which changes the left margin to 2 inches and jumps to page 10:

        JButton myButton= new JButton("My Button");
        printer.getPrintPreviewToolBar().add(myButton);

        myButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JTextField pageNumberTextField = (JTextField)printer.getPrintPreviewToolBar().getComponents()[7];
                printer.setLeftMargin(2.0);
                pageNumberTextField.setText("10");
 
               pageNumberTextField.postActionEvent(); // likewise, can call doClick() on buttons
            } } );

The print preview class creates the print preview toolbar once the first time you call getPrintPreviewToolBar(), returning a reference to this toolbar.  You can then modify this toolbar and/or the components contained within it, as above.   The print preview dialog uses this same toolbar each time it displays, so that the changes you make will then stay in effect.   There are three exceptions, however.  One is if you change locales during the running of your program.  In this case, all new strings for labels and tooltips must be read in and the toolbar is rebuilt, causing any changes you made previously to be lost.  The second is if you call setPrintPreviewString, since this also changes the strings and necessitates rebuilding the toolbar.  The third is if you change the value of setCrossPlatformDialogs(boolean), in which case the look and feel of the toolbar will be changed, requiring the toolbar to be rebuilt.

In addition to the above method for customizing the built-in J2PrinterWorks print preview dialog, the J2PrinterWorks product distribution includes the complete source code for two print preview dialogs.  One is the source code for a simple, single page print preview dialog with basic controls.  The other is the source code for the standard, full-featured J2PrinterWorks print preview dialog shown above.  Either of these may be customized by developers to create a print preview dialog with the features and appearance of their choosing.  See the documentation section entitled "Custom Print, Page Setup, and Print Preview dialogs".


Print to Image, HTML, PDF

Print to Image

J2Printer includes methods for "printing" formatted pages at screen resolution to an in-memory BufferedImage, suitable for constructing displays like the print preview dialog.  There is also a convenience method for saving any such BufferedImage to a JPEG (.jpg) file.  

The general-purpose print-to-image method is:

 getPageImage (Pageable pageable, int pageNumber, double scale, boolean outline, boolean reusable)
          
This method creates a BufferedImage representation of the specified page (1...n) of a specified Pageable at screen resolution with a given scale factor and optional black box drawn around the outside edge of the page.  The reusable flag indicates whether to allocate a new BufferedImage or reuse the BufferedImage space allocated in previous calls.

saveImageToJPEG (java.awt.image.BufferedImage image, java.lang.String fileName)
          
This method will save any BufferedImage, such as ones produced by getPageImage(), to a JPEG (.jpg) file.  Such a file is useful for inclusion in web pages, documentation, email attachments, etc.

To control whether the page images will be displayed in color or monochrome, the following method is available:

setPageImagesMonochrome(boolean monochrome)
          Method used in conjunction with the getPageImage methods, and thereby the print preview dialog page images, specifying whether the images are monochrome (gray scale) instead of color (default: false = color).


Print to HTML

J2Printer includes a method for "printing" a complete formatted document as a single HTML page or as an HTML slide show.  In either case the individual page images are generated as separate .jpg files in screen resolution at the specified scale.  The single HTML page just shows the entire series of page images in one long document.  The HTML slide show consists of a set of linked HTML pages, each containing an image of the next page of the document.  The HTML pages are displayed in an HTML frame set with a navigation bar on the left allowing for random access to any page.  In addition, each page image is linked to the next page, so clicking on each page of the document goes to the next page of the document as a slide show, whether the HTML pages are displayed in the frame set or by themselves.  To print to HTML, call the following method:

printToHTML(java.lang.String dir, java.lang.String file, double scale, boolean slideshow)
          Utility method for saving a facsimile of the printed document either a a single HTML page or as a series of HTML pages suitable for display in a browser as a slide show.

As of the J2PrinterWorks 4.2 release, the call to printToHTML honors the setSeparatePrintThread(boolean) method, so that by default this method executes in a background thread and fires print progress events.  Call setSeparatePrintThread(false) in advance of calling this method if you don't want this method to return until printing completes.


Print to PDF

J2Printer includes methods for "printing" a complete, formatted, J2PrinterWorks document to a .pdf file, Adobe's widely-used Portable Document Format. 

printToPDF(java.lang.String file)
          Utility method for saving a facsimile of the current document to a PDF file, suitable for viewing and/or printing by Adobe Acrobat Reader.

This "printToPDF" method requires that you include with your program a copy of the third-party, open source, "iText" library downloadable from http://www.lowagie.com/iText and available for free under MPL or LGPL licenses.  J2PrinterWorks is written so that the iText library is not required unless you wish to call either of the above two "printToPDF" methods and is not required to compile the J2PrinterWorks source code.

As of the J2PrinterWorks 4.2 release, the call to printToPDF honors the setSeparatePrintThread(boolean) method, so that by default this method executes in a background thread and fires print progress events.  Call setSeparatePrintThread(false) in advance of calling this method if you don't want this method to return until printing completes.

As a convenience on Windows systems, J2Printer also supports methods for printing a .pdf file to the default printer and displaying a .pdf file. 

printPDFFile(java.lang.String file)
          Utility method for printing the contents of a PDF file on the default printer (Windows only).  Uses a print dialog if isPrintDialogUsed() is true, otherwise prints to the default printer if using J2Printer or to the printer specified with setPrinter if using J2Printer14.

displayPDFFile(java.lang.String file)
          Utility method for displaying the contents of a PDF file using Adobe Acrobat Reader (Windows only).

Both these methods assume that you have installed Adobe Acrobat Reader on your system, available as a free download from http://www.adobe.com

A drawback to using Acrobat Reader for printing is that Acrobat Reader does not terminate when printing is completed.  We invoke Acrobat Reader with a minimized window so that the user initially doesn't see the Acrobat window, only (at your option) the print dialog.  However, if they print again, this time Acrobat Reader opens the minimized window.  This does not interfere with printing, but the user interface is less than ideal.  One alternative is to use the Ghostscript program "gsprint" to print.  The gsprint program can be invoked by Java from the command line using the Java "exec" method, for example:
    Runtime.getRuntime().exec("cmd.exe /c gsprint yourFile.pdf");
Other alternatives are to use Acrobat Reader but find and close the Acrobat window, or move it offscreen, or terminate the Acrobat application after printing.  These approaches, including source code for programs "pdfprint.c" and "pdfp.c" that implement them, are discussed in the thread at:
         http://forum.planetpdf.com/wb/default.asp?action=9&read=36960&fid=52#129012


Additional capabilities
 
Print progress events
The J2Printer class supports a number of print progress events that can be used to monitor the printing process.  Five of the events are PropertyChange events corresponding to changes in five properties that are maintained by J2Printer.  The five (read-only) properties are:

NOTE: The former J2Printer method isPrinting() was renamed to isPrintingUnderway() to avoid conflicts with the new JCompoent method isPrinting() added in JDK 1.6.

In addition, the following two events are supported without corresponding properties:

Your program can set up a PropertyChangeListener to listen to and key off of these property state changes.  Note that you need to either setSeparatePrintThread(true), which is the default, or have your PropertyChangeListener in a separate thread from the the code that calls J2Printer.print() , otherwise the print progress events will pile up and not get back to your application until printing completes.

Sample code for creating your own PropertyChangeListener would look like:

J2Printer printer = new J2Printer();
...
printer.addPropertyChangeListener(new PrintingStatusListener());
...
class PrintingStatusListener implements java.beans.PropertyChangeListener {      
    public void propertyChange(java.beans.PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals("printingUnderway")) {
            if (printer.isPrintingUnderway()) { }
// printing has started
            else { }                              // printing is done
        }

        if (evt.getPropertyName().equals("printDialogResponse")) {
            if (printer.isPrintDialogResponse()) { }  // if user said OK
            else { }                                  // if user said cancel
        }

        if (evt.getPropertyName().equals("pageBeingPrinted")) {
            // also get this event during printPreview, so test
            // isPrintingUnderway()==true to make sure we really are printing

            if (printer.isPrintingUnderway() && printer.getPageBeingPrinted()>0) { }
        }
    }
}


PrintingEventHandler
To make the printer event handling process easier, J2PrinterWorks includes a convenience class called PrintingEventHandler.  This class provides an implementation of PropertyChangeListener with stub (empty) methods for the main events of interest provided by J2PrinterWorks.  You can instantiate PrintingEventHandler and override any or all of its methods to invoke code of your choosing. 

Here is a complete example of using PrintingEventHandler (taken from J2PrinterWorksTestApplication):    

J2Printer printer = new J2Printer();
JLabel status = new JLabel(); // used for status report
...
printer.addPropertyChangeListener(new MyPrintingEventHandler());
...
class MyPrintingEventHandler extends PrintingEventHandler {
      int totalPages;

      public void printingStart() {
        showProgress("About to print..."); // printing started
        totalPages = printer.getPageable().getNumberOfPages(); // expensive so do only once
      }

      public void printingDone() {
        windowToFront(); // needed prior to JDK 1.4.1 due to Bug Parade #4514422
        brieflyShowProgress("Printing done");
      }

      public void printDialogOK() {
        windowToFront(); // needed prior to JDK 1.4.1 due to Bug Parade #4514422
        showProgress("Start printing...");
      }

      public void printDialogCanceled() {
        windowToFront(); // needed prior to JDK 1.4.1 due to Bug Parade #4514422
        brieflyShowProgress("Printing canceled");
      }

      public void pageSetupDialogOK() {
         brieflyShowProgress("Page setup dialog OK");
      }

      public void pageSetupDialogCanceled() {
         brieflyShowProgress("Page setup dialog canceled");
      }
 
      public void pageStart(int pageNum) {
        showProgress("Printing page " + pageNum + " of " + totalPages);
      }

      public void exceptionThrown(Exception e) {
        showProgress("Got an exception: " + e);
      }

}

private void showProgress(String str) { status.setText(str); } // where status is a JLabel

private void brieflyShowProgress(String str) {
      showProgress(str);
      new Thread() { public void run() {
          try { sleep(1500); } catch (Exception e) {}
          SwingUtilities.invokeLater( new Runnable() { public void run() { showProgress(" "); } } );
      } }.start(); // from different thread, wait 1 sec then erase
}


void windowToFront() { frame.toFront(); } // needed prior to JDK 1.4.1 due to Bug Parade #4514422


See the "PrintingEventHandler" section under "Utility Classes" for more examples.

Cloning
J2Printer includes a convenience method for cloning (copying) any Object in Java.  You may find it useful to print from a copy of your components for several reasons: 1) to avoid thread safety problems, 2) to control the appearance of your component as printed differently from the component as displayed, or 3) to modify your underlying component model (such as filling in missing values) before printing.  For such purposes J2Printer includes a general-purpose clone method:

    clone (java.lang.Object obj)

This method performs a "deep clone", i.e., all contained classes are recursively cloned as well.  Upon return, you need to cast the Object return value back to an Object of your type.  For example, you might copy a whole component:

    JTable cloneJTable = (JTable) clone(yourJTable); ;

or you might clone just the component's underlying model:

    TreeModel cloneTreeModel = (TreeModel) clone(yourJTree.getModel());
    JTree newJTree = new JTree();
    newJTree.setModel(cloneTreeModel);
 
If the object is not clonable, Java will throw a NotSerializableException.  The J2PrinterWorks clone method will catch this exception and rethrow it as a com.wildcrest.j2printerworks.CloneException, which is a subclass of RuntimeException and therefore may be optionally caught.


N-up printing
J2Printer supports "N-up" printing, where multiple page images can be printed together on each sheet of printed paper.  N-up printing supports 1, 2, 4, 6, 9, and 16 page images per printed page, with 2 and 6 being oriented landscape on the physical page and the rest oriented portrait.  The J2Printer print preview dialog will also reflect the current N-up setting.  To select N-up printing, call the following method:

setNup(int nup)
          Sets printing to use N-up formating (N page images per physical page), where N=1, 2, 4, 6, 9, or 16, or negative these same values which means suppress the drawing of the page outlines.


Page number of first page
J2Printer lets you select the page number to call the first page of your printed document.  This feature lets you print each chapter of a book as a separate document, with the page numbers of each chapter starting at an appropriate page number other than 1.  To specify the starting page number of your document, call the following method:

setStartingPageNumber(int startingPageNumber)
          Sets the starting page number, that is, the number used to number the first page of the document.


"Wait" cursor and parent frame
Depending upon the size and complexity of your document, the J2Printer print preview and print dialogs can take a few seconds to show up on the screen.  J2Printer will automatically display a "busy" or "wait" cursor (e.g. on Windows, a "watch" image) over your main window while this delay takes place if you identify the main window to J2Printer.  In addition, for the dialogs which are modal, this frame will be regarded as the "parent" frame with respect to hiding windows or bringing them to the front as a group.

setParentFrame(java.awt.Component parent)
          Set the parent Frame (or JFrame, JDialog, JWindow, JApplet, or JInternalFrame) from which the print dialog, print preview, and page setup modal dialogs are displayed and over which a "busy" cursor will be displayed as these dialogs are coming up.

In addition, J2Printer provides as a convenience the method it uses to display a "busy" cursor at any time over any window(s) of your choosing (a well-known tricky thing to do correctly in Java):

setBusyCursor(java.awt.Component parent, boolean busy)
          Convenience method that sets the cursor on your Frame (or JFrame, JDialog, JWindow, JApplet, or JInternalFrame) to Cursor.WAIT_CURSOR if busy is true, and to Cursor.DEFAULT_CURSOR if busy is false.


Locale and localization support
J2PrinterWorks.jar contains properties files for localizing the Print Preview dialog strings for the following locales: English, German, French, Spanish, Italian, Dutch, Japanese, Swedish, and Korean.  J2PrinterWorks uses the default locale of the machine it is running on to select the locale.  Or, your application can force a particular locale either by setting the overall locale for your application, for example:
      java.util.Locale.setDefault(java.util.Locale.FRANCE);
or by changing the locale just within J2PrinterWorks using the static setLocale method of J2Pageable:
      J2Pageable.setLocale(java.util.Locale.FRANCE);
You can use the properties files in J2PrinterWorks.jar to create more of your own for additional desired locales by following the syntax for specifying localized strings in these files.  If you add more properties files to your classpath (or back into J2PrinterWorks.jar), J2PrinterWorks will find and support them.  If J2PrinterWorks can't find a properties file for the current locale, it reverts to using English.  In addition, J2Printer has a method setPrintPreviewString which allows you to programmatically specify all the Print Preview strings regardless of locale (see Javadoc for J2Printer.setPrintPreviewString).  You can test all the standard J2PrinterWorks locales using the sample program J2TextPrinterTestApplication.


Debugging support
J2Printer has added a new method setDebug(boolean) which specifies whether stack trace and other debug information is to be printed to System.err when errors are encountered.  The default (new as of J2PrinterWorks 4.5) is setDebug(true) which ensures that all Java exceptions caught by J2Printer will cause something to print to System.err.  In addition, all exceptions caught by J2PrinterWorks, even those occuring in the background printing thread and therefore uncatchable from developer code, will fire a PrintingEventHandler exceptionThrown event (see PrintingEventHandler for how to handle exceptions caught by J2PrinterWorks).

setDebug(boolean debug)
          Specifies whether or not to print stack trace and debug information to System.err (default: true)


© Copyright 2009, Wildcrest Associates (http://www.wildcrest.com )