Example usage for java.awt.print Printable print

List of usage examples for java.awt.print Printable print

Introduction

In this page you can find the example usage for java.awt.print Printable print.

Prototype

int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException;

Source Link

Document

Prints the page at the specified index into the specified Graphics context in the specified format.

Usage

From source file:BookTest.java

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    PageFormat pageFormat = book.getPageFormat(currentPage);

    double xoff; // x offset of page start in window
    double yoff; // y offset of page start in window
    double scale; // scale factor to fit page in window
    double px = pageFormat.getWidth();
    double py = pageFormat.getHeight();
    double sx = getWidth() - 1;
    double sy = getHeight() - 1;
    if (px / py < sx / sy) // center horizontally
    {/*  www . j ava 2  s  . com*/
        scale = sy / py;
        xoff = 0.5 * (sx - scale * px);
        yoff = 0;
    } else
    // center vertically
    {
        scale = sx / px;
        xoff = 0;
        yoff = 0.5 * (sy - scale * py);
    }
    g2.translate((float) xoff, (float) yoff);
    g2.scale((float) scale, (float) scale);

    // draw page outline (ignoring margins)
    Rectangle2D page = new Rectangle2D.Double(0, 0, px, py);
    g2.setPaint(Color.white);
    g2.fill(page);
    g2.setPaint(Color.black);
    g2.draw(page);

    Printable printable = book.getPrintable(currentPage);
    try {
        printable.print(g2, pageFormat, currentPage);
    } catch (PrinterException e) {
        g2.draw(new Line2D.Double(0, 0, px, py));
        g2.draw(new Line2D.Double(px, 0, 0, py));
    }
}