Java Reference
In-Depth Information
Once you have a
PageFormat
object, you can modify the orientation of the page by calling its
setOrientation()
method as we have seen. The
PageFormat
class defines several methods to
retrieve information about the paper - we have seen that we can get the position and size of the
printable area on the page for instance by calling the
getImageableX()
,
getImageableY()
,
getImageableWidth()
, and
getImageableHeight()
methods. You also have
getWidth()
and
getHeight()
methods in the
PageFormat
class that return the overall width and height of the page.
These are all actually properties of the paper itself, which is represented by an object of the
Paper
class. You can also work with the
Paper
object for a
PageFormat
object directly.
Dealing with Paper
The
Paper
class encapsulates the size of the paper and the size and position of the printable area on the
page. The default constructor for the
Paper
class creates an American letter sized sheet with one inch
margins - the printable area being the area inside the margins. You can change the size of the paper by
calling the
setSize()
method for the
Paper
object as we'll see in a moment.
Rather than creating an independent
Paper
object, you will normally retrieve a reference to the
Paper
object for a
PageFormat
object by calling its
getPaper()
method. If you then want to change the
size of the paper or the printable area - the page margins in other words - you call the
setSize()
or
the
setImageableArea()
method for the
Paper
object. You can restore the paper details by passing
an object of type
Paper
back to the
PageFormat
object by calling its
setPaper()
method with a
reference to a
Paper
object as the argument.
The
setSize()
method for a
Paper
object has two parameters of type
double
that are the width and
height of the paper in units of 1/72 of an inch. If you use A4 paper, you could specify the size of the
paper for a
PageFormat
object with the following statements:
Paper paper = pageFormat.getPaper();
final double MM
_
TO
_
PAPER
_
UNITS = 1.0/25.4*72.0; // 25.4 mm to an inch
double widthA4 = 210*MM
_
TO
_
PAPER
_
UNITS;
double heightA4 = 297*MM
_
TO
_
PAPER
_
UNITS;
paper.setSize(widthA4, heightA4);
If you use letter size paper that is 8.5 by 11 inches, it's somewhat simpler:
Paper paper = pageFormat.getPaper();
double widthLetterSize = 72.0*8.5;
double heightLetterSize = 72.0*11.0;
paper.setSize(widthLetterSize, heightLetterSize);
The
setImageableArea()
method expects four arguments of type
double
to be supplied. The first two
are the coordinates of the top left corner of the printable area and the next two are the width and the height.
All these values are in units of 1/72 of an inch. To set 20 mm margins on your A4 sheet you could write:
double marginSize = 20.0* MM
_
TO
_
PAPER
_
UNITS; // 20 mm wide
paper.setImageableArea(marginSize, marginSize, // Top left
widthA4-2.0*marginSize, // Width
heightA4-2.0*marginSize); // Height