Java Reference
In-Depth Information
rightMargin *= 2.0; // ...and the right...
topMargin *= 2.0; // ...and the top...
bottomMargin *= 2.0; // ...and the bottom
paper.setImageableArea(leftMargin, topMargin, // Set new printable area
paper.getWidth()-leftMargin-rightMargin,
paper.getHeight()-topMargin-bottomMargin);
pageFormat.setPaper(paper); // Restore the paper
sketchBook.append(new SketchCoverPage(theApp), pageFormat);
Apart from the last statement that appends the
Printable
object that represents the page painter, all
this code is the same as in the previous example.
To add the second page of the sketch to the
Book
object, we could write:
pageFormat = PrinterJob.getPrinterJob().defaultPage(); // Get another default page
Rectangle rect = getModelExtent(); // Get sketch bounds
if(rect.width>rect.height) // If width is more
// than the height
pageFormat.setOrientation(pageFormat.LANDSCAPE); // ... set landscape
sketchBook.append(theApp.getView(), pageFormat); // Append the page
Now we have assembled the topic we can tell the
PrinterJob
object that we want to print the topic:
printJob.setPageable(sketchBook); // The topic is the
source of pages
Now all we need to do is call the
print()
method for the
PrinterJob
object to start printing. To
expedite printing, the
PrinterJob
will communicate with the
Book
object to get the number of pages
to be printed and to get the page painter and page format appropriate to print each page. The total
number of pages is returned by the
getNumberOfPages()
method for the
Book
object. A reference
to the
Printable
object for a given page index is returned by the
getPrintable()
method for the
Book
object and the
PageFormat
object for a given page index is returned by the
getPageFormat()
method. Obviously, in the case of Sketcher, using a
Book
object doesn't offer much advantage over the
Pageable
object that we used in the previous example. In situations where you have more complex
documents with a lot of pages with diverse formats it can make things much easier.
You use the other version of
append()
for a
Book
object to add a given number of pages to a book
that will be produced by a single
Printable
object, and where all the pages have the same format.
Here's an example:
Book book = new Book();
book.append(painter, pageFormat, pageCount);
Here the
painter
argument is a reference of type
Printable
that will print
pageCount
pages all
with the same format,
pageFormat
. A typical instance where you might use this might be a long text
document. The document could consist of many pages but they all are printed with the same page
format. The view object for the document would typically provide a method to figure out the number of
pages that are necessary to output the document.