Java Reference
In-Depth Information
public int print(Graphics g, // Graphics context for printing
PageFormat pageFormat, // The page format
int pageIndex) // Index number of current page
throws PrinterException {
if(pageIndex>0)
return NO _ SUCH _ PAGE;
Graphics2D g2D = (Graphics2D) g;
// Get sketch bounds
Rectangle rect = theApp.getModel().getModelExtent();
// If the width is more than the height, set landscape
if(rect.width>rect.height) {
pageFormat.setOrientation(pageFormat.LANDSCAPE);
// Now set the clip rectangle to the printable page area
g2D.setClip((int)pageFormat.getImageableX(), // x coordinate
(int)pageFormat.getImageableY(), // x coordinate
(int)pageFormat.getImageableWidth(), // width
(int)pageFormat.getImageableHeight()); // height
}
// Rest of the code as before...
}
The new rectangle defining the boundaries for clipping the output is exactly the printable area on the
page. We have to cast the coordinates and the width and height from double to int because that type
is required for the arguments to the setClip() method. If you recompile and try printing a sketch that
is wider than it is long, it should come out perfectly in landscape orientation.
User Page Setup
Of course, there are many situations where the best orientation from a paper usage point of view may
not be what the user wants. Instead of automatically setting landscape or portrait based on the
dimensions of a sketch, you could just provide the user with a dialog to select the page setup
parameters. The PrinterJob class makes this very easy since it provides a method to display the
dialog and set the user selections in a PageFormat object. To make use of this we could change the
printing code in the SketchFrame class like this:
PrinterJob printJob = PrinterJob.getPrinterJob(); // Get a printing object
PageFormat pageFormat = printJob.defaultPage(); // Get the page format
pageFormat = printJob.pageDialog(pageFormat); // Show page setup dialog
// Print using the user page format settings
printJob.setPrintable(theApp.getView(),pageFormat);
Search WWH ::




Custom Search