Printing in Java: Print Jobs, Multipage Printing and Print Services
Printing from Java: Printable and PrinterJob, print and page setup dialogs, PageFormat and Paper in points, banding and clipping, multipage output with Book and Pageable, print preview, javax.print services and document flavors, PostScript stream services, and printing attributes.
kvi5hnuCode Sprout team member17 min readOn this page
Printing in Java reuses everything from the Java 2D articles: a printed page is just another Graphics2D surface, and your drawing code does not care whether it paints a component, an image or a sheet of paper. On top of that, there are two APIs. The java.awt.print package (Java 1.2) drives a print job that asks your code to draw pages. The javax.print package (Java 1.4) finds printers, sends documents in standard formats (PostScript, PDF, images, text) and describes jobs with attributes derived from the Internet Printing Protocol.
Before writing your own printing code, check the shortcuts: JTable.print() (Java 5) prints a table across pages with optional header and footer text, and JTextComponent.print() (Java 6) prints the contents of any text component, both with a print dialog and a progress dialog included.
table.print(JTable.PrintMode.FIT_WIDTH,
new MessageFormat("Inventory"), new MessageFormat("Page {0}"));
textArea.print();
Printing a graphic
Two things are needed to print: an object that draws the pages, implementing Printable, and a print job, PrinterJob.
Printable has one method:
int print(Graphics g, PageFormat format, int pageIndex) throws PrinterException
The job calls it for each page with a graphics context for the paper, a description of the page and a page number starting at 0. The method draws the page and returns PAGE_EXISTS, or returns NO_SUCH_PAGE when pageIndex is past the last page, which ends the job.
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(printable);
var attributes = new HashPrintRequestAttributeSet();
if (job.printDialog(attributes)) { // false if the user canceled
try {
job.print(attributes);
} catch (PrinterException e) {
...
}
}
printDialog(attributes) shows a cross-platform dialog drawn by Swing, in which the user picks the printer, the pages, copies, paper and orientation; the choices are stored in the attribute set, which you pass on to print. Keeping the same set between print jobs remembers the user's settings. printDialog() without arguments shows the native dialog of the platform instead, which looks familiar to users but cannot report its settings as attributes. Since Java 7, adding DialogTypeSelection.NATIVE to the attribute set requests a native dialog while still using attributes, where the platform supports it. On a headless system the dialogs throw HeadlessException, but printing without a dialog still works.
Do not confuse PrinterJob with the class PrintJob from Java 1.1, which is obsolete, like the JobAttributes and PageAttributes classes that went with it.
The page is called more than once
Because a Printable does not tell the job how many pages there are, the job keeps asking until it gets NO_SUCH_PAGE. The print dialog therefore cannot show the real page range; it offers "1 to 1" or a large default. A Book (below) fixes that.
The job may call print several times for the same page. One reason is banding: to limit memory, the page can be rendered in horizontal strips, with the clip set to one strip at a time. Another is that the implementation first renders a page to learn what it contains (for example, whether it uses transparency, which PostScript cannot express) and then renders it for real. The demo shows the JDK's PostScript printer calling print twice for each page. Consequences:
- Never count pages in
print; use thepageIndexparameter. printmust draw the same page every time it is called with the same index, so do not advance iterators or other state while drawing.- Do not replace the clip. The context is clipped to the band and to the printable area; use
clipto restrict further, neversetClip, which could draw into the margins or outside the band.
Page formats and paper
The PageFormat parameter describes the page. Its measurements are in points, 1/72 of an inch (about 0.35 mm), the traditional unit of typesetting and the default unit of the printer's graphics context: a line drawn 72 units long is one inch long on paper.

getWidth()andgetHeight()are the size of the sheet: US Letter is 612 by 792 points, ISO A4 is about 595 by 842.- Printers cannot print to the edge, and users choose margins, so only the imageable area can be drawn on:
getImageableX(),getImageableY(),getImageableWidth()andgetImageableHeight(). The margins need not be symmetric.
The graphics context's origin is the corner of the paper, not of the imageable area. Most print methods therefore start by moving the origin:
g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
PageFormat combines a Paper (the physical sheet in portrait orientation, with its imageable area) with an orientation: PORTRAIT, LANDSCAPE or REVERSE_LANDSCAPE. In landscape, the PageFormat methods swap width and height for you, and the graphics context is already rotated, so drawing code needs no changes. getMatrix() reveals the rotation that maps landscape page coordinates to the paper.
var paper = new Paper(); // default: US Letter, one-inch margins
paper.setSize(595.28, 841.89); // A4
paper.setImageableArea(36, 36, 595.28 - 72, 841.89 - 72);
var format = new PageFormat();
format.setPaper(paper);
format.setOrientation(PageFormat.LANDSCAPE);
The job's defaultPage() returns the default format of the selected printer, which usually depends on the locale: Letter in the US and Canada, A4 almost everywhere else. validatePage(format) adjusts a format to what the printer can actually do.
To let users change paper and margins without printing, show a page setup dialog:
PageFormat chosen = job.pageDialog(attributes); // cross-platform; null if canceled
PageFormat nativeChoice = job.pageDialog(job.defaultPage()); // native; returns a modified copy
Sharing code between screen and paper
A component that should print what it shows calls one drawing method from both paintComponent and print:
class Chart extends JComponent implements Printable {
@Override protected void paintComponent(Graphics g) { drawChart((Graphics2D) g, getWidth(), getHeight()); }
@Override public int print(Graphics g, PageFormat pf, int page) {
if (page > 0) return NO_SUCH_PAGE;
var g2 = (Graphics2D) g;
g2.translate(pf.getImageableX(), pf.getImageableY());
drawChart(g2, pf.getImageableWidth(), pf.getImageableHeight());
return PAGE_EXISTS;
}
}
To print the visible surface of an existing component, call component.printAll(g2) inside print (after translating and possibly scaling); Swing's print methods disable double buffering, which is useless on paper. Because the printer context is vector based and has a high resolution, shapes and text print sharply at any scale, while images print at their own pixel resolution.
Printing several pages
Real documents have many pages, and the job should know how many. A Pageable describes a whole document: its number of pages and, for each page, a PageFormat and a Printable. The JDK's implementation is Book, a list of sections:
var book = new Book();
book.append(coverPage, pageFormat); // one page
book.append(bodyPages, pageFormat, bodyPageCount); // several pages drawn by one Printable
job.setPageable(book);
The print dialog now shows the correct range, and the user can print parts of it. Different sections may even use different page formats, for example a landscape table inside a portrait report.
Two difficulties come with a Book:
- You must know each section's page count before printing, so the content must be laid out in advance: measure text, find the page breaks, keep the result for printing. If the user changes the page format, redo the layout.
- The
pageIndexpassed to a section'sPrintableis the page number within the book, not within the section. A section that starts on page 1 must subtract 1. In the demo, the banner'sprintreceives indexes 1 to 5.
Measuring needs font metrics, and the printer's graphics context only exists during printing. A practical solution is to lay out with a device-independent FontRenderContext (new FontRenderContext(null, true, true): no transform, antialiasing and fractional metrics on), whose metrics scale linearly, as the listing does.
A banner
A banner prints a drawing so large that it spans many pages, which are then taped together. The layout step computes a scale so that the drawing fills the imageable height, and the page count from the scaled width:
double scale = pf.getImageableHeight() / drawingHeight;
int pages = (int) Math.ceil(scale * drawingWidth / pf.getImageableWidth());
Printing page n is pure Java 2D: translate to the imageable area, clip to it, shift the drawing left by n imageable widths, scale, and draw the whole thing. The clip discards everything except the slice for this page, so characters or shapes cut by a page break are no problem.
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.clip(new Rectangle2D.Double(0, 0, pf.getImageableWidth(), pf.getImageableHeight()));
g2.translate(-n * pf.getImageableWidth(), 0);
g2.scale(scale, scale);
g2.fill(drawing);
Print preview
A print preview is the same trick applied to the screen: in a component's paintComponent, scale the graphics context so that a page fits the component, paint a white rectangle for the paper, and call the page's Printable with that context. Because the drawing code only sees a Graphics2D and a PageFormat, it produces the same picture on screen as on paper. The demo renders each page of its book this way into small images.
Print services
The javax.print API works at a different level: it sends documents to print services, without dialogs and without your drawing code, if the data is already in a format a printer understands. That makes it suitable for server-side printing, such as printing shipping labels when an order arrives.
A document flavor combines a data type (MIME type) with the Java representation of the data. DocFlavor has nested classes for the representations, each with constants for the types:
| Representation | Example flavors | Data |
|---|---|---|
INPUT_STREAM, URL, BYTE_ARRAY | GIF, JPEG, PNG, PDF, POSTSCRIPT, PCL, TEXT_PLAIN_UTF_8, TEXT_HTML_UTF_8, AUTOSENSE | Bytes in a document format |
READER, STRING, CHAR_ARRAY | TEXT_PLAIN, TEXT_HTML | Characters |
SERVICE_FORMATTED | PRINTABLE, PAGEABLE, RENDERABLE_IMAGE | Java objects that draw themselves |
AUTOSENSE means raw bytes that are passed to the printer unchanged, for printer languages such as PCL, ZPL for label printers or ESC/POS for receipt printers.
To print, look up the services that accept the flavor, pick one, create a job and print a Doc:
DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, attributes); // attributes may be null
PrintService service = services.length > 0 ? services[0] : PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = service.createPrintJob();
try (var in = Files.newInputStream(path)) {
job.print(new SimpleDoc(in, flavor, null), new HashPrintRequestAttributeSet());
}
Whether a service accepts PDF or images directly depends on the printer and the operating system's print system; check service.isDocFlavorSupported(flavor) or getSupportedDocFlavors(). SERVICE_FORMATTED flavors are always supported, because Java renders them itself. A PrinterJob can be pointed at a specific service with setPrintService, and PrinterJob.lookupPrintServices() lists the services it can use. ServiceUI.printDialog shows a print dialog for a list of services. getName() returns the printer name to show users.
DocPrintJob.addPrintJobListener registers a PrintJobListener that is told when data has been transferred, when the job completes, fails or is canceled, or that the service will send no more events; how many of these events arrive depends on the service.
Stream print services
A stream print service produces the print data in a stream instead of sending it to a printer. The JDK includes one that converts Printable, Pageable and image flavors to PostScript, and it works on any system, even without printers or a display:
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
StreamPrintServiceFactory[] factories =
StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, "application/postscript");
try (var out = Files.newOutputStream(Path.of("banner.ps"))) {
StreamPrintService service = factories[0].getPrintService(out);
service.createPrintJob().print(new SimpleDoc(book, flavor, null), null);
}
A StreamPrintService is a PrintService, so everything else stays the same. The resulting file can be viewed and converted to PDF with tools such as Ghostscript. The JDK has no PDF stream service; to create PDF from Java 2D drawing, use a library (Apache PDFBox and OpenPDF provide Graphics2D adapters) or print to the operating system's PDF printer.
Printing attributes
The javax.print.attribute package describes everything about printing with attributes, mostly taken from the Internet Printing Protocol (IPP/1.1, RFC 8011, which replaced RFC 2911). There are four roles:
- Print request attributes ask for something for the whole job: copies, paper, orientation, two-sided printing.
- Doc attributes ask for something for one document in a job.
- Print service attributes report on the printer: its name, make and model, whether it accepts jobs, its state.
- Print job attributes report on a job: its state, how many pages were printed.
Each role is an interface extending Attribute (PrintRequestAttribute, DocAttribute, PrintServiceAttribute, PrintJobAttribute), and an attribute class implements those that apply. Copies, for example, is both a request attribute (print 10 copies) and a job attribute (10 copies were printed). A fifth interface, SupportedValuesAttribute, marks attributes that describe capabilities, such as CopiesSupported (1 to 99 copies).
Attributes are collected in attribute sets: HashPrintRequestAttributeSet, HashDocAttributeSet, HashPrintServiceAttributeSet, HashPrintJobAttributeSet and the general HashAttributeSet. A typed set accepts only attributes of its role; adding Copies to a doc attribute set throws ClassCastException.
An attribute set works like a map keyed by the attribute's category, a Class object returned by getCategory(). For Copies, the category is Copies.class, and adding a second Copies replaces the first. Categories can be shared: MediaSizeName, MediaName and MediaTray all have the category Media, because a job can have only one of them.
var attributes = new HashPrintRequestAttributeSet();
attributes.add(new Copies(2));
attributes.add(MediaSizeName.ISO_A4);
attributes.add(OrientationRequested.LANDSCAPE);
attributes.add(Sides.DUPLEX);
attributes.add(new PageRanges("1-3, 5"));
var copies = (Copies) attributes.get(Copies.class);
Attribute values come in a few shapes, expressed by their superclasses:
IntegerSyntax:Copies,NumberUp,JobPriority,JobImpressions, ...TextSyntax:JobName,PrinterName,PrinterLocation,PrinterMakeAndModel,RequestingUserName, ...DateTimeSyntax:DateTimeAtCreation,DateTimeAtCompleted,JobHoldUntil, ...URISyntax:Destination,PrinterURI,PrinterMoreInfo, ...SetOfIntegerSyntax:PageRangesand the...Supportedranges.ResolutionSyntax:PrinterResolution.Size2DSyntax:MediaSize.EnumSyntax, for a fixed set of values that are constants of the class:Chromaticity(MONOCHROME,COLOR),PrintQuality(DRAFT,NORMAL,HIGH),OrientationRequested(PORTRAIT,LANDSCAPE,REVERSE_PORTRAIT,REVERSE_LANDSCAPE),Sides(ONE_SIDED,DUPLEX=TWO_SIDED_LONG_EDGE,TUMBLE=TWO_SIDED_SHORT_EDGE),SheetCollate,Finishings(STAPLE,BIND,SADDLE_STITCH, ...),MediaTray,JobState,PrinterState,Fidelity,MultipleDocumentHandling,PresentationDirection,JobSheetsand many more. Compare them with==.
Paper deserves a note, because three classes are involved: MediaSizeName names a paper size (ISO_A4, NA_LETTER, NA_LEGAL, the ISO A, B and C series, envelopes) and is what you put in a request; MediaSize holds the actual dimensions, with lookups MediaSize.ISO.A4, getMediaSizeForName(name) and findMedia(x, y, units), which finds the closest standard size; and MediaPrintableArea requests the printable area. MediaSize.getX(MediaSize.MM) and getX(MediaSize.INCH) convert units.
A printer need not support every attribute. PrintService.getSupportedAttributeCategories(), isAttributeCategorySupported, getSupportedAttributeValues(category, flavor, attributes) and isAttributeValueSupported query its capabilities; getDefaultAttributeValue reports its defaults; getAttributes() returns its current service attributes (such as PrinterIsAcceptingJobs and QueuedJobCount), and DocPrintJob.getAttributes() the job's. Adding Fidelity.FIDELITY_TRUE makes the job fail instead of silently ignoring a request the printer cannot fulfill.
A banner printer
This program prints the outline of a message as a banner over several pages, with a cover page stating the page count. It offers page setup, a print preview, printing with the cross-platform dialog, and saving the job as PostScript through the stream print service. Layout uses a device-independent font render context, so the page count is the same for the preview, the printer and the PostScript file.
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.*;
import java.awt.print.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.JobName;
import javax.swing.*;
public final class BannerPrinter extends JFrame {
private static final long serialVersionUID = 1L;
private static final Font FONT = new Font(Font.SERIF, Font.BOLD, 72);
// layout with a device-independent context: fractional metrics, no hinting differences
private static final FontRenderContext LAYOUT_CONTEXT = new FontRenderContext(null, true, true);
private final JTextField text = new JTextField("Happy Birthday!", 30);
private final transient PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
private transient PageFormat pageFormat;
/** Prints the outline of a message across as many pages as its width requires. */
static final class Banner implements Printable {
private final String message;
private final int firstPage;
Banner(String message, int firstPage) {
this.message = message;
this.firstPage = firstPage;
}
private Rectangle2D bounds() {
return new TextLayout(message, FONT, LAYOUT_CONTEXT).getBounds();
}
double scale(PageFormat pf) { return pf.getImageableHeight() / bounds().getHeight(); }
int pageCount(PageFormat pf) {
return (int) Math.ceil(scale(pf) * bounds().getWidth() / pf.getImageableWidth());
}
@Override public int print(Graphics g, PageFormat pf, int pageIndex) {
int page = pageIndex - firstPage; // Book passes the page number within the book
if (page < 0 || page >= pageCount(pf)) return NO_SUCH_PAGE;
var g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.translate(pf.getImageableX(), pf.getImageableY());
drawCropMarks(g2, pf.getImageableWidth(), pf.getImageableHeight());
g2.clip(new Rectangle2D.Double(0, 0, pf.getImageableWidth(), pf.getImageableHeight()));
g2.translate(-page * pf.getImageableWidth(), 0);
double s = scale(pf);
g2.scale(s, s);
Rectangle2D b = bounds();
var layout = new TextLayout(message, FONT, LAYOUT_CONTEXT);
g2.setStroke(new BasicStroke(1.5f / (float) s)); // about 1.5 points after scaling
g2.draw(layout.getOutline(AffineTransform.getTranslateInstance(-b.getX(), -b.getY())));
g2.dispose();
return PAGE_EXISTS;
}
private static void drawCropMarks(Graphics2D g2, double w, double h) {
final double c = 18; // a quarter inch
double[][] corners = {{0, 0, 1, 1}, {w, 0, -1, 1}, {0, h, 1, -1}, {w, h, -1, -1}};
for (double[] k : corners) {
g2.draw(new Line2D.Double(k[0], k[1], k[0] + k[2] * c, k[1]));
g2.draw(new Line2D.Double(k[0], k[1], k[0], k[1] + k[3] * c));
}
}
}
static final class CoverPage implements Printable {
private final String title;
CoverPage(String title) { this.title = title; }
@Override public int print(Graphics g, PageFormat pf, int pageIndex) {
if (pageIndex != 0) return NO_SUCH_PAGE;
var g2 = (Graphics2D) g;
g2.setPaint(Color.BLACK);
g2.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 14));
g2.drawString(title, (float) pf.getImageableX(), (float) (pf.getImageableY() + 14));
return PAGE_EXISTS;
}
}
/** Shows the pages of a book, scaled to fit, using the same Printable code as the printer. */
static final class PreviewCanvas extends JComponent {
private static final long serialVersionUID = 1L;
private final transient Book book;
private int page;
PreviewCanvas(Book book) {
this.book = book;
setPreferredSize(new Dimension(500, 400));
}
void flip(int by) {
page = Math.clamp(page + by, 0, book.getNumberOfPages() - 1);
repaint();
}
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g.create();
PageFormat pf = book.getPageFormat(page);
double scale = Math.min((getWidth() - 20) / pf.getWidth(), (getHeight() - 20) / pf.getHeight());
g2.translate((getWidth() - scale * pf.getWidth()) / 2, (getHeight() - scale * pf.getHeight()) / 2);
g2.scale(scale, scale);
var paper = new Rectangle2D.Double(0, 0, pf.getWidth(), pf.getHeight());
g2.setPaint(Color.WHITE);
g2.fill(paper);
g2.setPaint(Color.GRAY);
g2.draw(paper);
g2.setPaint(Color.BLACK);
try {
book.getPrintable(page).print(g2, pf, page);
} catch (PrinterException e) {
g2.draw(new Line2D.Double(0, 0, pf.getWidth(), pf.getHeight()));
}
g2.dispose();
}
}
public BannerPrinter() {
super("Banner Printer");
var buttons = new JPanel();
buttons.add(button("Page setup...", this::pageSetup));
buttons.add(button("Preview...", this::preview));
buttons.add(button("Print...", this::print));
buttons.add(button("Save PostScript", this::savePostScript));
add(text, BorderLayout.NORTH);
add(buttons, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
}
private static JButton button(String label, Runnable action) {
var b = new JButton(label);
b.addActionListener(_ -> action.run());
return b;
}
private void pageSetup() {
PageFormat chosen = PrinterJob.getPrinterJob().pageDialog(attributes); // cross-platform dialog
if (chosen != null) pageFormat = chosen;
}
private Book makeBook() {
if (pageFormat == null) pageFormat = PrinterJob.getPrinterJob().defaultPage();
var book = new Book();
var banner = new Banner(text.getText().isBlank() ? " " : text.getText(), 1);
int pages = banner.pageCount(pageFormat);
book.append(new CoverPage(text.getText() + " (" + pages + " banner pages)"), pageFormat);
book.append(banner, pageFormat, pages);
return book;
}
private void preview() {
var canvas = new PreviewCanvas(makeBook());
var dialog = new JDialog(this, "Print Preview", true);
var nav = new JPanel();
nav.add(button("Previous", () -> canvas.flip(-1)));
nav.add(button("Next", () -> canvas.flip(1)));
nav.add(button("Close", dialog::dispose));
dialog.add(canvas, BorderLayout.CENTER);
dialog.add(nav, BorderLayout.SOUTH);
dialog.pack();
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
}
private void print() {
PrinterJob job = PrinterJob.getPrinterJob();
job.setJobName("Banner");
job.setPageable(makeBook()); // the dialog shows the real page range
if (!job.printDialog(attributes)) return; // the user canceled
try {
job.print(attributes);
} catch (PrinterException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Printing failed", JOptionPane.ERROR_MESSAGE);
}
}
private void savePostScript() {
var chooser = new JFileChooser();
if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
StreamPrintServiceFactory[] factories =
StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, "application/postscript");
if (factories.length == 0) {
JOptionPane.showMessageDialog(this, "No PostScript stream service");
return;
}
try (OutputStream out = new FileOutputStream(chooser.getSelectedFile())) {
StreamPrintService service = factories[0].getPrintService(out);
var request = new HashPrintRequestAttributeSet();
request.add(new JobName("Banner", null));
service.createPrintJob().print(new SimpleDoc(makeBook(), flavor, null), request);
} catch (IOException | PrintException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Saving failed", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new BannerPrinter().setVisible(true));
}
}
The banner's print method works on a copy of the graphics context, so the scaling and clipping do not affect anything the print system draws afterwards. The stroke width is divided by the scale factor so that the outline is about 1.5 points wide on paper, whatever the scale. The print preview passes the book page index, exactly as the printer does.
The program
The demo explores page formats, media sizes and attribute sets, then prints a book (a cover page and a banner) through the PostScript stream service into memory, and finally previews every page by calling the same Printable objects with an image's graphics context. It needs no printer and no display.
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.awt.print.*;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
public class Solution {
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
Locale.setDefault(Locale.US); // the default paper depends on the locale
pageFormats();
mediaSizes();
attributes();
streamPrinting();
}
static String r(double v) { return "%.1f".formatted(v); }
static String describe(PageFormat pf) {
return "page " + r(pf.getWidth()) + " x " + r(pf.getHeight()) + ", imageable area at (" + r(pf.getImageableX())
+ ", " + r(pf.getImageableY()) + ") size " + r(pf.getImageableWidth()) + " x " + r(pf.getImageableHeight());
}
static void pageFormats() {
System.out.println("== Paper and PageFormat (units: points, 72 per inch) ==");
var pf = new PageFormat();
System.out.println("default: " + describe(pf));
var a4 = new Paper();
a4.setSize(595.28, 841.89); // 210 x 297 mm
a4.setImageableArea(36, 36, 595.28 - 72, 841.89 - 72); // half-inch margins
pf.setPaper(a4);
System.out.println("A4: " + describe(pf));
pf.setOrientation(PageFormat.LANDSCAPE);
System.out.println("landscape: " + describe(pf));
System.out.println("landscape matrix " + Arrays.toString(pf.getMatrix())
+ ": rotated 90 degrees, so drawing code needs no changes");
System.out.println("1 inch = 72 points = 25.4 mm; 1 mm = " + r(72 / 25.4) + " points");
}
static void mediaSizes() {
System.out.println();
System.out.println("== Media sizes ==");
MediaSize a4 = MediaSize.ISO.A4, letter = MediaSize.NA.LETTER;
System.out.println("ISO A4: " + r(a4.getX(MediaSize.MM)) + " x " + r(a4.getY(MediaSize.MM)) + " mm = "
+ r(a4.getX(MediaSize.INCH) * 72) + " x " + r(a4.getY(MediaSize.INCH) * 72) + " points");
System.out.println("NA Letter: " + letter.getX(MediaSize.INCH) + " x " + letter.getY(MediaSize.INCH)
+ " inches, name " + letter.getMediaSizeName());
System.out.println("size of ISO_A5: " + r(MediaSize.getMediaSizeForName(MediaSizeName.ISO_A5).getX(MediaSize.MM))
+ " mm wide; closest name to 209 x 296 mm: " + MediaSize.findMedia(209, 296, MediaSize.MM));
}
static void attributes() {
System.out.println();
System.out.println("== Attribute sets ==");
PrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
set.add(new Copies(2));
set.add(new Copies(3)); // same category: replaces
set.add(MediaSizeName.ISO_A4);
set.add(OrientationRequested.LANDSCAPE);
set.add(Sides.DUPLEX);
set.add(new PageRanges("1-3, 5"));
set.add(new JobName("banner", null));
Attribute[] all = set.toArray();
Arrays.sort(all, java.util.Comparator.comparing(Attribute::getName));
for (Attribute attr : all)
System.out.printf(" %-22s category %-21s value %s%n", attr.getName(), attr.getCategory().getSimpleName(), attr);
var copies = (Copies) set.get(Copies.class);
System.out.println("copies: " + copies.getValue() + "; DUPLEX is TWO_SIDED_LONG_EDGE: "
+ (Sides.DUPLEX == Sides.TWO_SIDED_LONG_EDGE) + "; page 4 in range: "
+ ((PageRanges) set.get(PageRanges.class)).contains(4));
System.out.println("Copies is a PrintRequestAttribute " + (copies instanceof PrintRequestAttribute)
+ " and a PrintJobAttribute " + (copies instanceof PrintJobAttribute)
+ ", but no DocAttribute " + DocAttribute.class.isInstance(copies));
try {
new HashDocAttributeSet().add(new Copies(1));
} catch (ClassCastException e) {
System.out.println("adding Copies to a DocAttributeSet: ClassCastException");
}
}
/** The banner shape: an arrow 600 units long and 100 units high, with a notched tail. */
static Shape bannerShape() {
var path = new Path2D.Double();
path.moveTo(0, 25);
path.lineTo(470, 25);
path.lineTo(470, 0);
path.lineTo(600, 50);
path.lineTo(470, 100);
path.lineTo(470, 75);
path.lineTo(0, 75);
path.lineTo(40, 50);
path.closePath();
return path;
}
/** A banner that spreads the shape over as many pages as needed at full page height. */
static final class Banner implements Printable {
final List<String> calls = new ArrayList<>();
private final int firstPage; // book page index of the banner's first page
Banner(int firstPage) { this.firstPage = firstPage; }
static double scale(PageFormat pf) { return pf.getImageableHeight() / 100; }
static int pageCount(PageFormat pf) {
return (int) Math.ceil(600 * scale(pf) / pf.getImageableWidth());
}
@Override public int print(Graphics g, PageFormat pf, int pageIndex) {
calls.add(String.valueOf(pageIndex));
int page = pageIndex - firstPage; // the book passes its own page numbers
if (page < 0 || page >= pageCount(pf)) return NO_SUCH_PAGE;
var g2 = (Graphics2D) g.create();
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.clip(new Rectangle2D.Double(0, 0, pf.getImageableWidth(), pf.getImageableHeight()));
g2.translate(-page * pf.getImageableWidth(), 0); // shift earlier pages out to the left
g2.scale(scale(pf), scale(pf));
g2.fill(bannerShape());
g2.dispose();
return PAGE_EXISTS;
}
}
static final class Cover implements Printable {
@Override public int print(Graphics g, PageFormat pf, int pageIndex) {
if (pageIndex != 0) return NO_SUCH_PAGE;
var g2 = (Graphics2D) g;
g2.draw(new Rectangle2D.Double(pf.getImageableX(), pf.getImageableY(),
pf.getImageableWidth(), pf.getImageableHeight())); // a frame around the printable area
double size = Math.min(pf.getImageableWidth(), pf.getImageableHeight()) / 2;
g2.fill(new Ellipse2D.Double(pf.getImageableX() + (pf.getImageableWidth() - size) / 2,
pf.getImageableY() + (pf.getImageableHeight() - size) / 2, size, size));
return PAGE_EXISTS;
}
}
/** Renders one book page scaled into a small image, the way a print preview does. */
static String[] preview(Book book, int page, int w, int h) throws PrinterException {
PageFormat pf = book.getPageFormat(page);
var image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = image.createGraphics();
g.scale(w / pf.getWidth(), h / pf.getHeight());
g.setColor(Color.WHITE);
g.setStroke(new BasicStroke(0f)); // hairline: visible at any scale
book.getPrintable(page).print(g, pf, page);
g.dispose();
String[] rows = new String[h];
for (int y = 0; y < h; y++) {
var sb = new StringBuilder();
for (int x = 0; x < w; x++) sb.append(image.getRaster().getSample(x, y, 0) > 0 ? '#' : '.');
rows[y] = sb.toString();
}
return rows;
}
static void streamPrinting() throws Exception {
System.out.println();
System.out.println("== A book printed with a stream print service ==");
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
StreamPrintServiceFactory[] factories =
StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, "application/postscript");
System.out.println("factories producing PostScript from a Pageable: " + factories.length);
// page format: A4 landscape with half-inch margins
var paper = new Paper();
paper.setSize(595.28, 841.89);
paper.setImageableArea(36, 36, 595.28 - 72, 841.89 - 72);
var pf = new PageFormat();
pf.setPaper(paper);
pf.setOrientation(PageFormat.LANDSCAPE);
var book = new Book();
book.append(new Cover(), pf); // page 0
var banner = new Banner(1);
int bannerPages = Banner.pageCount(pf);
book.append(banner, pf, bannerPages); // pages 1 .. bannerPages
System.out.println("banner scale " + r(Banner.scale(pf)) + ", width " + r(600 * Banner.scale(pf))
+ " points, imageable width " + r(pf.getImageableWidth()) + " -> " + bannerPages + " banner pages, "
+ book.getNumberOfPages() + " pages in the book");
var out = new ByteArrayOutputStream();
StreamPrintService service = factories[0].getPrintService(out);
System.out.println("service: " + service.getName() + ", output format " + service.getOutputFormat());
DocPrintJob job = service.createPrintJob();
var request = new HashPrintRequestAttributeSet();
request.add(new JobName("banner", null));
job.print(new SimpleDoc(book, flavor, null), request);
String ps = out.toString(java.nio.charset.StandardCharsets.ISO_8859_1);
System.out.println("PostScript output starts with " + ps.lines().findFirst().orElse("")
+ ", " + ps.lines().filter(l -> l.startsWith("%%Page:")).count() + " %%Page: comments");
System.out.println("banner print() calls with page index: " + banner.calls + " (each page twice)");
System.out.println("print preview, every page scaled to 42 x 15 characters:");
int pages = book.getNumberOfPages();
String[][] pictures = new String[pages][];
for (int i = 0; i < pages; i++) pictures[i] = preview(book, i, 42, 15);
for (int start = 0; start < pages; start += 2) {
for (int y = 0; y < 15; y++) {
var sb = new StringBuilder(" ");
for (int i = start; i < Math.min(start + 2, pages); i++) sb.append(pictures[i][y]).append(" ");
System.out.println(sb.toString().stripTrailing());
}
System.out.println();
}
}
}
== Paper and PageFormat (units: points, 72 per inch) ==
default: page 612.0 x 792.0, imageable area at (72.0, 72.0) size 468.0 x 648.0
A4: page 595.3 x 841.9, imageable area at (36.0, 36.0) size 523.3 x 769.9
landscape: page 841.9 x 595.3, imageable area at (36.0, 36.0) size 769.9 x 523.3
landscape matrix [0.0, -1.0, 1.0, 0.0, 0.0, 841.89]: rotated 90 degrees, so drawing code needs no changes
1 inch = 72 points = 25.4 mm; 1 mm = 2.8 points
== Media sizes ==
ISO A4: 210.0 x 297.0 mm = 595.3 x 841.9 points
NA Letter: 8.5 x 11.0 inches, name na-letter
size of ISO_A5: 148.0 mm wide; closest name to 209 x 296 mm: iso-a4
== Attribute sets ==
copies category Copies value 3
job-name category JobName value banner
media category Media value iso-a4
orientation-requested category OrientationRequested value landscape
page-ranges category PageRanges value 1-3,5
sides category Sides value two-sided-long-edge
copies: 3; DUPLEX is TWO_SIDED_LONG_EDGE: true; page 4 in range: false
Copies is a PrintRequestAttribute true and a PrintJobAttribute true, but no DocAttribute false
adding Copies to a DocAttributeSet: ClassCastException
== A book printed with a stream print service ==
factories producing PostScript from a Pageable: 1
banner scale 5.2, width 3139.7 points, imageable width 769.9 -> 5 banner pages, 6 pages in the book
service: Postscript output, output format application/postscript
PostScript output starts with %!PS-Adobe-3.0, 6 %%Page: comments
banner print() calls with page index: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5] (each page twice)
print preview, every page scaled to 42 x 15 characters:
.......................................... ..........................................
..#######################################. ..........................................
..#.....................................#. ..........................................
..#.....................................#. ..........................................
..#.....................................#. ..........................................
..#..............#########..............#. .....###################################..
..#.............###########.............#. ........################################..
..#............#############............#. ...........#############################..
..#............#############............#. ...........#############################..
..#.............###########.............#. ........################################..
..#..............#########..............#. .....###################################..
..#.....................................#. ..........................................
..#.....................................#. ..........................................
..#.....................................#. ..........................................
..#######################################. ..........................................
.......................................... ..........................................
.......................................... ..........................................
.......................................... ..........................................
.......................................... ..........................................
.......................................... ..........................................
..######################################.. ..######################################..
..######################################.. ..######################################..
..######################################.. ..######################################..
..######################################.. ..######################################..
..######################################.. ..######################################..
..######################################.. ..######################################..
.......................................... ..........................................
.......................................... ..........................................
.......................................... ..........................................
.......................................... ..........................................
.......................................... ..........................................
.......................................... ..........................................
..........#####........................... ..........................................
..........###########..................... ..........................................
..........################................ ..........................................
..#############################........... ..........................................
..##################################...... ..........................................
..######################################.. ..#.......................................
..######################################.. ..#.......................................
..##################################...... ..........................................
..#############################........... ..........................................
..........################................ ..........................................
..........###########..................... ..........................................
..........#####........................... ..........................................
.......................................... ..........................................
Points to notice:
- The default
PageFormatis US Letter with one-inch margins; in landscape, width and height and the imageable values swapped, and the matrix shows the 90-degree rotation. findMediamapped 209 x 296 mm to the closest standard size, A4.- The second
Copiesreplaced the first, because both have the categoryCopies; the typed doc attribute set rejectedCopies. - The banner arrow was scaled 5.2 times to fill the landscape page height, making it 3140 points wide and needing 5 pages; the last one holds only the very tip of the arrow, because the page count is rounded up.
- The PostScript output has one
%%Page:comment per book page, and the print system called the banner'sprinttwice for every page, with book page indexes 1 to 5. - The preview shows the cover's frame around the imageable area and the arrow continuing from page to page.
Common questions
How do I print a Swing component?
For tables and text components, use the built-in methods: table.print() and textComponent.print() show the print dialog and handle pagination. For other components, write a Printable that translates to the imageable area, scales to fit, and calls component.printAll(g).
How do I create a PDF instead of printing? The JDK can't write PDF directly, but every major operating system offers a "Save as PDF" or "Microsoft Print to PDF" printer in the print dialog. For programmatic PDF generation, use a library such as Apache PDFBox or OpenPDF.
Why is my printout tiny or cut off?
Printing coordinates are in points (1/72 inch), and the page has margins. Translate by pageFormat.getImageableX()/getImageableY() and scale your content to getImageableWidth()/getImageableHeight().
Why is print called several times for the same page?
The print system may render each page more than once (for example in bands). Your Printable must be stateless per page, producing the same output for the same page index every time.
How do I print without showing a dialog?
Call job.print() without printDialog(). It uses the default printer and settings. Use PrintServiceLookup to choose a specific printer and a PrintRequestAttributeSet for copies, orientation or paper size.
API reference
| Class / method | Purpose |
|---|---|
Printable.print(g, pageFormat, pageIndex), PAGE_EXISTS, NO_SUCH_PAGE | Drawing pages. |
PrinterJob.getPrinterJob, setPrintable, setPageable, printDialog(attributes), printDialog(), print(attributes), pageDialog, defaultPage, validatePage, setJobName, setPrintService, lookupPrintServices, cancel | Print jobs. |
PageFormat.getWidth/getHeight, getImageableX/Y/Width/Height, getOrientation, setOrientation, setPaper, getMatrix; PORTRAIT, LANDSCAPE, REVERSE_LANDSCAPE | Page description. |
Paper.setSize, setImageableArea, getImageableX/... | The physical sheet. |
Pageable.getNumberOfPages/getPageFormat/getPrintable; Book.append(printable, format), append(printable, format, pages) | Multipage documents. |
JTable.print(mode, header, footer), JTextComponent.print(), Component.printAll | Printing components. |
PrintServiceLookup.lookupPrintServices(flavor, attributes), lookupDefaultPrintService, ServiceUI.printDialog | Finding print services. |
PrintService.getName, createPrintJob, isDocFlavorSupported, getSupportedDocFlavors, getSupportedAttributeValues, isAttributeValueSupported, getAttributes | Print services. |
DocFlavor.INPUT_STREAM.PDF/PNG/..., DocFlavor.SERVICE_FORMATTED.PRINTABLE/PAGEABLE, DocFlavor.BYTE_ARRAY.AUTOSENSE | Document flavors. |
DocPrintJob.print(doc, attributes), addPrintJobListener, getAttributes; SimpleDoc(data, flavor, attributes) | Printing documents. |
StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, mimeType), getPrintService(out), StreamPrintService.getOutputFormat | Printing to a stream (PostScript). |
HashPrintRequestAttributeSet, HashDocAttributeSet, HashPrintServiceAttributeSet, HashPrintJobAttributeSet; add, get(category), remove, toArray | Attribute sets. |
Attribute.getCategory, getName; Copies, MediaSizeName, MediaSize, MediaPrintableArea, OrientationRequested, Sides, PageRanges, PrintQuality, Chromaticity, JobName, Fidelity, DialogTypeSelection | Common attributes. |
Summary
- Implement
Printableto draw pages, usingpageIndexfrom 0, and print with aPrinterJob; showprintDialogandpageDialogwith an attribute set to keep user settings. - Page measurements are in points (1/72 inch). Translate to the imageable area, never replace the clip, and expect
printto be called several times per page. - For multipage output, lay out first and give the job a
Book, whose sections receive book-wide page numbers. A print preview calls the samePrintablewith a scaled screen context. javax.printsends documents of aDocFlavortoPrintServices found by lookup; stream print services produce PostScript files without a printer.- Attributes, based on IPP, describe requests, documents, services and jobs; sets are keyed by category, and services report which values they support.
Practice Questions
1. A Printable increments a counter each time print is called and uses it to decide which part of a report to draw. On some printers, parts of the report are missing. Why?
The print system may call print more than once for the same page, for example to render a page in bands or to analyze a page before rendering it. Each extra call advances the counter, so later pages draw the wrong part, or parts are skipped. print must depend only on its pageIndex parameter and on layout computed in advance, and must render the same output for the same index every time.
2. What is the advantage of setPageable(book) over setPrintable(printable)?
With a Printable, the job does not know the number of pages until print returns NO_SUCH_PAGE, so the print dialog cannot offer the correct page range. A Pageable such as Book states the number of pages and a page format and printable for each page in advance, so users can choose page ranges, and sections can use different page formats. The price is that the content must be laid out before printing starts.
3. A print method draws a box at (0, 0) with the size of getImageableWidth() by getImageableHeight(). On paper, the box's left and top edges are missing and it ends short on the right and bottom. What is wrong?
The origin of the printer's graphics context is the corner of the paper, not of the imageable area. The box starts in the margin, where the clip discards its left and top edges, and it ends imageableX/imageableY short of the imageable area's right and bottom edges. Call g2.translate(pf.getImageableX(), pf.getImageableY()) before drawing.
4. How can a server application without a display produce a printable file of a Java 2D drawing?
Use a stream print service: look up StreamPrintServiceFactory.lookupStreamPrintServiceFactories(DocFlavor.SERVICE_FORMATTED.PRINTABLE, "application/postscript"), get a service for an output stream with getPrintService(out), and print a SimpleDoc wrapping the Printable. This works headless and without printers. The result is PostScript, which tools such as Ghostscript convert to PDF; for direct PDF output, use a PDF library with a Graphics2D adapter.
5. A program adds new Copies(2) and later new Copies(5) to the same request attribute set. How many copies are requested, and why?
Five. An attribute set holds at most one attribute per category, and the category of both Copies objects is Copies.class, so the second add replaces the first. The same applies to shared categories: adding MediaSizeName.ISO_A4 and then MediaTray.MANUAL keeps only the tray, because both belong to the category Media.
Previous: Raster Images in Java: ImageIO, BufferedImage Pixels and Image Filters
Related reading
- Raster Images in Java: ImageIO, BufferedImage Pixels and Image Filters
- Java 2D Strokes, Paint, Transforms, Clipping and Transparency
- Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry
- Swing Trees: JTree, Tree Models, Nodes and Paths
- Swing Table Cell Renderers and Editors: Custom Rendering and Editing

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.