# Tutorial: iText by Example

## Graphics2D

The java.awt.Graphics2D object:
Maybe you really don't want to learn to use PDF Syntax, maybe you really don't want to learn a complete new API such as iText, maybe you just want to stick to what you know, in casu, the JAVA API of the JSDK. No problem. In that case, we have a class that exactly meets your needs: PdfGraphics2D. This class extends java.awt.Graphics2D and overrides its methods so that they produce PDF syntax. Isn't that nice? (Before you ask: there's also a PdfGraphics2D object extending java.awt.print.PrinterGraphics.)
There are several createGraphics methods in class PdfContentByte. In the example below, I copied the code of an example in SUN's Graphics2D tutorial literally. The Graphics2D object I used, was retrieved from a PdfTemplate:

     PdfContentByte cb = writer.getDirectContent();
    PdfTemplate tp = cb.createTemplate(w, h);
    Graphics2D g2 = tp.createGraphics(w, h, new DefaultFontMapper());

Example: java com.lowagie.examples.directcontent.graphics2D.G2D
A Simple Graphics2D example: see graphics2D.pdf
So if you already know all about Graphics2D in JAVA or if you have programs writing stuff to a Graphics2D object (for instance to a JPanel in some JFrame), you don't need to learn all about the PDF syntax, you can use your existing code to write your output to PDF! For instance, if you are familiar with java.awt.Font, but not that familiar with the Fonts in iText/PDF, you could use PdfGraphics2D as is done in the next example:
Example: java com.lowagie.examples.directcontent.graphics2D.ArabicText
Drawing arabic text using the Graphics2D object: see arabictext.pdf
The only syntax you need to know is this:

    java.awt.Font font = new java.awt.Font("arial", 0, 18);
    PdfContentByte cb = writer.getDirectContent();
    java.awt.Graphics2D g2 =
        cb.createGraphicsShapes(PageSize.A4.width(), PageSize.A4.height());
    g2.setFont(font);
    g2.drawString(text, 100, 100);
    g2.dispose();

DO NOT FORGET to call PdfGraphics2D.dispose()!!!
A good example of how iText can be plugged in into another library that makes extensive use of Graphics2D can be found at JFree.org. JFree.org is the home of JFreeChart, one of the most used libraries for creating Charts. Charts are written to a java.awt.Graphics2D objects, so if you want to have those charts in PDF, just plug in iText:
Example: java com.lowagie.examples.directcontent.graphics2D.JFreeChartExample
Some JFreeChart examples: see barchart.pdf piechart.pdf xychart.pdf
Extra jars needed in your CLASSPATH: jfreechart.jar jcommon.jar
If you have an Free/Open Source Software application that uses iText in this context, please send me an example, so I can add it to this chapter.
Go to top of the page
Amazon books:
amazon.co.uk-link