print

Print shapes example

In this tutorial we are going to show how you can print simple shapes in paper using your printer. We are going to use some basic classes from AWT.

The basic steps we go through this example are:

  • Create a custom class that extends Component and implements Printable
  • Override the paint method of Component class. Inside that method create a simple shape, in this case a RoundRectangle2D object and perform the graphic transformations you wish to it
  • Override the print method of Printable interface set up the printable area and paint the shape
  • Create a normal PrinterJob
  • Launch a printDialog so the user can choose the specifications of the printing (landscape mode and several printer settings…)
Let’s take a look at the code snippet bellow:
package com.javacodegeeks.snippets.desktop;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintShapes{

    public static void main(String[] args) {

        PrinterJob printerJob = PrinterJob.getPrinterJob();

        PageFormat pageFormat = printerJob.defaultPage();

// For landscape we should use PageFormat.LANDSCAPE instead

        pageFormat.setOrientation(PageFormat.PORTRAIT);

// Show page format dialog with page format settings

        pageFormat = printerJob.pageDialog(pageFormat);

        printerJob.setPrintable(new CustomPaintComponent(), pageFormat);

        try {

            // Show print dialog to allow the user to change the default printer settings

            if (printerJob.printDialog()) {

                printerJob.print();

            }

        } catch (PrinterException e) {

            System.out.println("Printer exception : " + e.getMessage());

        }

    }

    /**
     * To draw on the screen, it is first necessary to subclass a Component and
     * override its paint() method. The paint() method is automatically called
     * by the windowing system whenever component's area needs to be repainted.
     * To print a component it is necessary to implement the print(...) method
     * of the Printable interface.
     */
    static class CustomPaintComponent extends Component implements Printable {

        @Override
        public void paint(Graphics g) {

// Retrieve the graphics context; this object is used to paint shapes

            Graphics2D g2d = (Graphics2D) g;

            /**
             *
             * The coordinate system of a graphics context is such that the
             * origin is at the * northwest corner and x-axis increases toward
             * the right while the y-axis increases * toward the bottom.
             *
             */
            int x = 0;

            int y = 0;

            int w = getSize().width - 1;

            int h = getSize().height - 1;

            Shape roundRectangle = new RoundRectangle2D.Float(x, y, w, h, w / 2, h / 2);

            AffineTransform affineTransform = new AffineTransform();

            affineTransform.scale(0.6, 0.4);

            affineTransform.shear(0.3, 0.7);

            affineTransform.translate(w / 4, h / 4);

            affineTransform.rotate(0.12);

            Shape newRoundRectangle = affineTransform.createTransformedShape(roundRectangle);

            g2d.draw(roundRectangle);

            g2d.draw(newRoundRectangle);

        }

        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {

// We assume the page exists until proven otherwise

            int retval = Printable.PAGE_EXISTS;

// We only want to deal with the first page. The first page is numbered '0'

            if (pageIndex > 0) {

                return Printable.NO_SUCH_PAGE;

            }

            Graphics2D g2d = (Graphics2D) graphics;

// The area of the printable area

            double ix = pageFormat.getImageableX();

            double iy = pageFormat.getImageableY();

            double iw = pageFormat.getImageableWidth();

            double ih = pageFormat.getImageableHeight();

            /**
             *
             * Note that (0, 0) of the Graphics object is at the top-left of the
             * actual page,
             *
             * outside the printable area. In this example, the Graphics object
             * is translated * so that (0, 0) becomes the top-left corner of the
             * printable area.
             *
             */
            g2d.translate(ix, iy);

// We populate the Graphics object from CustomPaintComponent's paint() method

            paint(g2d);

            return retval;

        }
    }
}

 
This was an example on how to Print Shapes in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button