Chapter 14: The imaging model

This is a code example of iText PDF, discover more.

10th October 2015
admin-marketing

Switch code for this example

GetContentStream.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part4.chapter14;

import java.io.FileOutputStream;
import java.io.IOException;

import part1.chapter01.HelloWorld;
import part1.chapter05.Hero1;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;

public class GetContentStream {
    /** The content stream of a first PDF. */
    public static final String RESULT1
        = "results/part4/chapter14/contentstream1.txt";
    /** The content stream of a second PDF. */
    public static final String RESULT2
        = "results/part4/chapter14/contentstream2.txt";
    
    /**
     * Reads the content stream of the first page of a PDF into a text file.
     * @param src    the path to a PDF file
     * @param result the path to the resulting text file
     * @throws IOException
     */
    public void readContent(String src, String result) throws IOException {
        PdfReader reader = new PdfReader(src);
        FileOutputStream out = new FileOutputStream(result);
        out.write(reader.getPageContent(1));
        out.flush();
        out.close();
        reader.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new HelloWorld().createPdf(HelloWorld.RESULT);
        new Hero1().createPdf(Hero1.RESULT);
        GetContentStream example = new GetContentStream();
        example.readContent(HelloWorld.RESULT, RESULT1);
        example.readContent(Hero1.RESULT, RESULT2);
    }
}
PathConstructionAndPainting.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.GrayColor;

public class PathConstructionAndPainting {

    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/paths.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        // draw squares
        createSquares(canvas, 50, 720, 80, 20);
        ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
            new Phrase(
                "Methods moveTo(), lineTo(), stroke(), closePathStroke(), fill(), and closePathFill()"),
                50, 700, 0);
        // draw Bezier curves
        createBezierCurves(canvas, 70, 600, 80, 670, 140, 690, 160, 630, 160);
        ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
            new Phrase("Different curveTo() methods, followed by stroke()"), 50, 580, 0);
        // draw stars and circles
        createStarsAndCircles(canvas, 50, 470, 40, 20);
        ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
            new Phrase("Methods fill(), eoFill(), newPath(), fillStroke(), and eoFillStroke()"),
                50, 450, 0);
        // draw different shapes using convenience methods
        canvas.saveState();
        canvas.setColorStroke(new GrayColor(0.2f));
        canvas.setColorFill(new GrayColor(0.9f));
        canvas.arc(50, 270, 150, 330, 45, 270);
        canvas.ellipse(170, 270, 270, 330);
        canvas.circle(320, 300, 30);
        canvas.roundRectangle(370, 270, 80, 60, 20);
        canvas.fillStroke();
        canvas.restoreState();
        Rectangle rect = new Rectangle(470, 270, 550, 330);
        rect.setBorderWidthBottom(10);
        rect.setBorderColorBottom(new GrayColor(0f));
        rect.setBorderWidthLeft(4);
        rect.setBorderColorLeft(new GrayColor(0.9f));
        rect.setBackgroundColor(new GrayColor(0.4f));
        canvas.rectangle(rect);
        ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
            new Phrase("Convenience methods"), 50, 250, 0);
        // step 5
        document.close();
    }
    
    /**
     * Draws a row of squares.
     * @param canvas the canvas to which the squares have to be drawn
     * @param x      X coordinate to position the row
     * @param y      Y coordinate to position the row
     * @param side   the side of the square
     * @param gutter the space between the squares
     */
    public void createSquares(PdfContentByte canvas,
        float x, float y, float side, float gutter) {
        canvas.saveState();
        canvas.setColorStroke(new GrayColor(0.2f));
        canvas.setColorFill(new GrayColor(0.9f));
        canvas.moveTo(x, y);
        canvas.lineTo(x + side, y);
        canvas.lineTo(x + side, y + side);
        canvas.lineTo(x, y + side);
        canvas.stroke();
        x = x + side + gutter;
        canvas.moveTo(x, y);
        canvas.lineTo(x + side, y);
        canvas.lineTo(x + side, y + side);
        canvas.lineTo(x, y + side);
        canvas.closePathStroke();
        x = x + side + gutter;
        canvas.moveTo(x, y);
        canvas.lineTo(x + side, y);
        canvas.lineTo(x + side, y + side);
        canvas.lineTo(x, y + side);
        canvas.fill();
        x = x + side + gutter;
        canvas.moveTo(x, y);
        canvas.lineTo(x + side, y);
        canvas.lineTo(x + side, y + side);
        canvas.lineTo(x, y + side);
        canvas.fillStroke();
        x = x + side + gutter;
        canvas.moveTo(x, y);
        canvas.lineTo(x + side, y);
        canvas.lineTo(x + side, y + side);
        canvas.lineTo(x, y + side);
        canvas.closePathFillStroke();
        canvas.restoreState();
    }
    
    /**
     * Draws a series of Bezier curves
     * @param cb the canvas to which the curves have to be drawn
     * @param x0 X coordinate of the start point
     * @param y0 Y coordinate of the start point
     * @param x1 X coordinate of the first control point
     * @param y1 Y coordinate of the first control point
     * @param x2 X coordinate of the second control point
     * @param y2 Y coordinate of the second control point
     * @param x3 X coordinate of the end point
     * @param y3 Y coordinate of the end point
     * @param distance the distance between the curves
     */
    public void createBezierCurves(PdfContentByte cb, float x0, float y0,
        float x1, float y1, float x2, float y2, float x3, float y3, float distance) {
        cb.moveTo(x0, y0);
        cb.lineTo(x1, y1);
        cb.moveTo(x2, y2);
        cb.lineTo(x3, y3);
        cb.moveTo(x0, y0);
        cb.curveTo(x1, y1, x2, y2, x3, y3);
        x0 += distance;
        x1 += distance;
        x2 += distance;
        x3 += distance;
        cb.moveTo(x2, y2);
        cb.lineTo(x3, y3);
        cb.moveTo(x0, y0);
        cb.curveTo(x2, y2, x3, y3);
        x0 += distance;
        x1 += distance;
        x2 += distance;
        x3 += distance;
        cb.moveTo(x0, y0);
        cb.lineTo(x1, y1);
        cb.moveTo(x0, y0);
        cb.curveTo(x1, y1, x3, y3);
        cb.stroke();

    }
    
    /**
     * Draws a row of stars and circles.
     * @param canvas the canvas to which the shapes have to be drawn
     * @param x      X coordinate to position the row
     * @param y      Y coordinate to position the row
     * @param radius the radius of the circles
     * @param gutter the space between the shapes
     */
    public static void createStarsAndCircles(PdfContentByte canvas,
        float x, float y, float radius, float gutter) {
        canvas.saveState();
        canvas.setColorStroke(new GrayColor(0.2f));
        canvas.setColorFill(new GrayColor(0.9f));
        createStar(canvas, x, y);
        createCircle(canvas, x + radius, y - 70, radius, true);
        createCircle(canvas, x + radius, y - 70, radius / 2, true);
        canvas.fill();
        x += 2 * radius + gutter;
        createStar(canvas, x, y);
        createCircle(canvas, x + radius, y - 70, radius, true);
        createCircle(canvas, x + radius, y - 70, radius / 2, true);
        canvas.eoFill();
        x += 2 * radius + gutter;
        createStar(canvas, x, y);
        canvas.newPath();
        createCircle(canvas, x + radius, y - 70, radius, true);
        createCircle(canvas, x + radius, y - 70, radius / 2, true);
        x += 2 * radius + gutter;
        createStar(canvas, x, y);
        createCircle(canvas, x + radius, y - 70, radius, true);
        createCircle(canvas, x + radius, y - 70, radius / 2, false);
        canvas.fillStroke();
        x += 2 * radius + gutter;
        createStar(canvas, x, y);
        createCircle(canvas, x + radius, y - 70, radius, true);
        createCircle(canvas, x + radius, y - 70, radius / 2, true);
        canvas.eoFillStroke();
        canvas.restoreState();
    }
    
    /**
     * Creates a path for a five pointed star.
     * This method doesn't fill or stroke the star!
     * @param canvas the canvas for which the star is constructed
     * @param x      the X coordinate of the center of the star
     * @param y      the Y coordinate of the center of the star
     */
    public static void createStar(PdfContentByte canvas, float x, float y) {
        canvas.moveTo(x + 10, y);
        canvas.lineTo(x + 80, y + 60);
        canvas.lineTo(x, y + 60);
        canvas.lineTo(x + 70, y);
        canvas.lineTo(x + 40, y + 90);
        canvas.closePath();
    }
 
    /**
     * Creates a path for circle using Bezier curvers.
     * The path can be constructed clockwise or counter-clockwise.
     * This method doesn't fill or stroke the circle!
     * @param canvas    the canvas for which the path is constructed 
     * @param x         the X coordinate of the center of the circle
     * @param y         the Y coordinate of the center of the circle
     * @param r         the radius
     * @param clockwise true if the circle has to be constructed clockwise
     */
    public static void createCircle(PdfContentByte canvas, float x, float y,
        float r, boolean clockwise) {
        float b = 0.5523f;
        if (clockwise) {
            canvas.moveTo(x + r, y);
            canvas.curveTo(x + r, y - r * b, x + r * b, y - r, x, y - r);
            canvas.curveTo(x - r * b, y - r, x - r, y - r * b, x - r, y);
            canvas.curveTo(x - r, y + r * b, x - r * b, y + r, x, y + r);
            canvas.curveTo(x + r * b, y + r, x + r, y + r * b, x + r, y);
        } else {
            canvas.moveTo(x + r, y);
            canvas.curveTo(x + r, y + r * b, x + r * b, y + r, x, y + r);
            canvas.curveTo(x - r * b, y + r, x - r, y + r * b, x - r, y);
            canvas.curveTo(x - r, y - r * b, x - r * b, y - r, x, y - r);
            canvas.curveTo(x + r * b, y - r, x + r, y - r * b, x + r, y);
        }
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new PathConstructionAndPainting().createPdf(RESULT);
    }
}
GraphicsStateOperators.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

public class GraphicsStateOperators {

    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/graphics_state.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        
        // line widths
        canvas.saveState();
        for (int i = 25; i > 0; i--) {
            canvas.setLineWidth((float) i / 10);
            canvas.moveTo(50, 806 - (5 * i));
            canvas.lineTo(320, 806 - (5 * i));
            canvas.stroke();
        }
        canvas.restoreState();
        
        // line cap
        canvas.moveTo(350, 800);
        canvas.lineTo(350, 750);
        canvas.moveTo(540, 800);
        canvas.lineTo(540, 750);
        canvas.stroke();
        
        canvas.saveState();
        canvas.setLineWidth(8);
        canvas.setLineCap(PdfContentByte.LINE_CAP_BUTT);
        canvas.moveTo(350, 790);
        canvas.lineTo(540, 790);
        canvas.stroke();
        canvas.setLineCap(PdfContentByte.LINE_CAP_ROUND);
        canvas.moveTo(350, 775);
        canvas.lineTo(540, 775);
        canvas.stroke();
        canvas.setLineCap(PdfContentByte.LINE_CAP_PROJECTING_SQUARE);
        canvas.moveTo(350, 760);
        canvas.lineTo(540, 760);
        canvas.stroke();
        canvas.restoreState();
        
        // join miter
        canvas.saveState();
        canvas.setLineWidth(8);
        canvas.setLineJoin(PdfContentByte.LINE_JOIN_MITER);
        canvas.moveTo(387, 700);
        canvas.lineTo(402, 730);
        canvas.lineTo(417, 700);
        canvas.stroke();
        canvas.setLineJoin(PdfContentByte.LINE_JOIN_ROUND);
        canvas.moveTo(427, 700);
        canvas.lineTo(442, 730);
        canvas.lineTo(457, 700);
        canvas.stroke();
        canvas.setLineJoin(PdfContentByte.LINE_JOIN_BEVEL);
        canvas.moveTo(467, 700);
        canvas.lineTo(482, 730);
        canvas.lineTo(497, 700);
        canvas.stroke();
        canvas.restoreState();

        // line dash
        canvas.saveState();
        canvas.setLineWidth(3);
        canvas.moveTo(50, 660);
        canvas.lineTo(320, 660);
        canvas.stroke();
        canvas.setLineDash(6, 0);
        canvas.moveTo(50, 650);
        canvas.lineTo(320, 650);
        canvas.stroke();
        canvas.setLineDash(6, 3);
        canvas.moveTo(50, 640);
        canvas.lineTo(320, 640);
        canvas.stroke();
        canvas.setLineDash(15, 10, 5);
        canvas.moveTo(50, 630);
        canvas.lineTo(320, 630);
        canvas.stroke();
        float[] dash1 = { 10, 5, 5, 5, 20 };
        canvas.setLineDash(dash1, 5);
        canvas.moveTo(50, 620);
        canvas.lineTo(320, 620);
        canvas.stroke();
        float[] dash2 = { 9, 6, 0, 6 };
        canvas.setLineCap(PdfContentByte.LINE_CAP_ROUND);
        canvas.setLineDash(dash2, 0);
        canvas.moveTo(50, 610);
        canvas.lineTo(320, 610);
        canvas.stroke();
        canvas.restoreState();

        // miter limit
        PdfTemplate hooks = canvas.createTemplate(300, 120);
        hooks.setLineWidth(8);
        hooks.moveTo(46, 50);
        hooks.lineTo(65, 80);
        hooks.lineTo(84, 50);
        hooks.stroke();
        hooks.moveTo(87, 50);
        hooks.lineTo(105, 80);
        hooks.lineTo(123, 50);
        hooks.stroke();
        hooks.moveTo(128, 50);
        hooks.lineTo(145, 80);
        hooks.lineTo(162, 50);
        hooks.stroke();
        hooks.moveTo(169, 50);
        hooks.lineTo(185, 80);
        hooks.lineTo(201, 50);
        hooks.stroke();
        hooks.moveTo(210, 50);
        hooks.lineTo(225, 80);
        hooks.lineTo(240, 50);
        hooks.stroke();
        
        canvas.saveState();
        canvas.setMiterLimit(2);
        canvas.addTemplate(hooks, 300, 600);
        canvas.restoreState();
        
        canvas.saveState();
        canvas.setMiterLimit(2.1f);
        canvas.addTemplate(hooks, 300, 550);
        canvas.restoreState();
        // step 5
        document.close();
    }
        
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new GraphicsStateOperators().createPdf(RESULT);
    }
}
TransformationMatrix1.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

public class TransformationMatrix1 {

    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/transformation_matrix1.pdf";
    /** A PDF with the iText logo that will be transformed. */
    public static final String RESOURCE = "resources/pdfs/logo.pdf";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Rectangle rect = new Rectangle(-595, -842, 595, 842);
        Document document = new Document(rect);
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        // draw the coordinate system
        PdfContentByte canvas = writer.getDirectContent();
        canvas.moveTo(-595, 0);
        canvas.lineTo(595, 0);
        canvas.moveTo(0, -842);
        canvas.lineTo(0, 842);
        canvas.stroke();
        // Read the PDF containing the logo
        PdfReader reader = new PdfReader(RESOURCE);
        PdfTemplate template = writer.getImportedPage(reader, 1);
        // add it at different positions using different transformations
        canvas.saveState();
        canvas.addTemplate(template, 0, 0);
        canvas.concatCTM(0.5f, 0, 0, 0.5f, -595, 0);
        canvas.addTemplate(template, 0, 0);
        canvas.concatCTM(1, 0, 0, 1, 595, 595);
        canvas.addTemplate(template, 0, 0);
        canvas.restoreState();

        canvas.saveState();
        canvas.concatCTM(1, 0, 0.4f, 1, -750, -650);
        canvas.addTemplate(template, 0, 0);
        canvas.restoreState();
        
        canvas.saveState();
        canvas.concatCTM(0, -1, -1, 0, 650, 0);
        canvas.addTemplate(template, 0, 0);
        canvas.concatCTM(0.2f, 0, 0, 0.5f, 0, 300);
        canvas.addTemplate(template, 0, 0);
        canvas.restoreState();
        // step 5
        document.close();
        reader.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new TransformationMatrix1().createPdf(RESULT);
    }
}
TransformationMatrix2.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

public class TransformationMatrix2 {

    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/transformation_matrix2.pdf";
    /** A PDF with the iText logo that will be transformed. */
    public static final String RESOURCE = "resources/pdfs/logo.pdf";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Rectangle rect = new Rectangle(-595, -842, 595, 842);
        Document document = new Document(rect);
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        // draw the coordinate system
        PdfContentByte canvas = writer.getDirectContent();
        canvas.moveTo(-595, 0);
        canvas.lineTo(595, 0);
        canvas.moveTo(0, -842);
        canvas.lineTo(0, 842);
        canvas.stroke();
        
        // read the PDF with the logo
        PdfReader reader = new PdfReader(RESOURCE);
        PdfTemplate template = writer.getImportedPage(reader, 1);
        // add it at different positions using different transformations
        canvas.addTemplate(template, 0, 0);
        canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -595, 0);
        canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -297.5f, 297.5f);
        canvas.addTemplate(template, 1, 0, 0.4f, 1, -750, -650);
        canvas.addTemplate(template, 0, -1, -1, 0, 650, 0);
        canvas.addTemplate(template, 0, -0.2f, -0.5f, 0, 350, 0);
        // step 5
        document.close();
        reader.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new TransformationMatrix2().createPdf(RESULT);
    }
}
TransformationMatrix3.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.awt.geom.AffineTransform;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

public class TransformationMatrix3 {

    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/transformation_matrix3.pdf";
    /** A PDF with the iText logo that will be transformed */
    public static final String RESOURCE = "resources/pdfs/logo.pdf";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Rectangle rect = new Rectangle(-595, -842, 595, 842);
        Document document = new Document(rect);
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        // draw coordinate system
        canvas.moveTo(-595, 0);
        canvas.lineTo(595, 0);
        canvas.moveTo(0, -842);
        canvas.lineTo(0, 842);
        canvas.stroke();
        // read the PDF with the logo
        PdfReader reader = new PdfReader(RESOURCE);
        PdfTemplate template = writer.getImportedPage(reader, 1);
        // add it
        canvas.saveState();
        canvas.addTemplate(template, 0, 0);
        AffineTransform af = new AffineTransform();
        af.translate(-595, 0);
        af.scale(0.5, 0.5);
        canvas.transform(af);
        canvas.addTemplate(template, 0, 0);
        canvas.concatCTM(AffineTransform.getTranslateInstance(595, 595));
        canvas.addTemplate(template, 0, 0);
        canvas.restoreState();

        canvas.saveState();
        af = new AffineTransform(1, 0, 0.4, 1, -750, -650);
        canvas.addTemplate(template, af);
        canvas.restoreState();
        
        canvas.saveState();
        af = new AffineTransform(0, -1, -1, 0, 650, 0);
        canvas.addTemplate(template, af);
        af = new AffineTransform(0, -0.2f, -0.5f, 0, 350, 0);
        canvas.addTemplate(template, af);
        canvas.restoreState();
        // step 5
        document.close();
        reader.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new TransformationMatrix3().createPdf(RESULT);
    }
}
TextStateOperators.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfTextArray;
import com.itextpdf.text.pdf.PdfWriter;

public class TextStateOperators {

    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/text_operators.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        String text = "AWAY again";
        BaseFont bf = BaseFont.createFont();
        canvas.beginText();
        // line 1
        canvas.setFontAndSize(bf, 16);
        canvas.moveText(36, 806);
        canvas.moveTextWithLeading(0, -24);
        canvas.showText(text);
        // line 2
        canvas.setWordSpacing(20);
        canvas.newlineShowText(text);
        // line 3
        canvas.setCharacterSpacing(10);
        canvas.newlineShowText(text);
        canvas.setWordSpacing(0);
        canvas.setCharacterSpacing(0);
        // line 4
        canvas.setHorizontalScaling(50);
        canvas.newlineShowText(text);
        canvas.setHorizontalScaling(100);
        // line 5
        canvas.newlineShowText(text);
        canvas.setTextRise(15);
        canvas.setFontAndSize(bf, 12);
        canvas.setColorFill(BaseColor.RED);
        canvas.showText("2");
        canvas.setColorFill(GrayColor.GRAYBLACK);
        // line 6
        canvas.setLeading(56);
        canvas.newlineShowText("Changing the leading: " + text);
        canvas.setLeading(24);
        canvas.newlineText();
        // line 7
        PdfTextArray array = new PdfTextArray("A");
        array.add(120);
        array.add("W");
        array.add(120);
        array.add("A");
        array.add(95);
        array.add("Y again");
        canvas.showText(array);
        canvas.endText();

        canvas.setColorFill(BaseColor.BLUE);
        canvas.beginText();
        canvas.setTextMatrix(360, 770);
        canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
        canvas.setFontAndSize(bf, 24);
        canvas.showText(text);
        canvas.endText();

        canvas.beginText();
        canvas.setTextMatrix(360, 730);
        canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);
        canvas.setFontAndSize(bf, 24);
        canvas.showText(text);
        canvas.endText();

        canvas.beginText();
        canvas.setTextMatrix(360, 690);
        canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
        canvas.setFontAndSize(bf, 24);
        canvas.showText(text);
        canvas.endText();

        canvas.beginText();
        canvas.setTextMatrix(360, 650);
        canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
        canvas.setFontAndSize(bf, 24);
        canvas.showText(text);
        canvas.endText();

        PdfTemplate template = canvas.createTemplate(200, 36);
        template.setLineWidth(2);
        for (int i = 0; i < 6; i++) {
            template.moveTo(0, i * 6);
            template.lineTo(200, i * 6);
        }
        template.stroke();
        
        canvas.saveState();
        canvas.beginText();
        canvas.setTextMatrix(360, 610);
        canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_CLIP);
        canvas.setFontAndSize(bf, 24);
        canvas.showText(text);
        canvas.endText();
        canvas.addTemplate(template, 360, 610);
        canvas.restoreState();

        canvas.saveState();
        canvas.beginText();
        canvas.setTextMatrix(360, 570);
        canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE_CLIP);
        canvas.setFontAndSize(bf, 24);
        canvas.showText(text);
        canvas.endText();
        canvas.addTemplate(template, 360, 570);
        canvas.restoreState();

        canvas.saveState();
        canvas.beginText();
        canvas.setTextMatrix(360, 530);
        canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE_CLIP);
        canvas.setFontAndSize(bf, 24);
        canvas.showText(text);
        canvas.endText();
        canvas.addTemplate(template, 360, 530);
        canvas.restoreState();
        
        canvas.saveState();
        canvas.beginText();
        canvas.setTextMatrix(360, 490);
        canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_CLIP);
        canvas.setFontAndSize(bf, 24);
        canvas.showText(text);
        canvas.endText();
        canvas.addTemplate(template, 360, 490);
        canvas.restoreState();

        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new TextStateOperators().createPdf(RESULT);
    }

}
TextMethods.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class TextMethods {

    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/text_methods.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        // draw helper lines
        PdfContentByte cb = writer.getDirectContent();
        cb.setLineWidth(0f);
        cb.moveTo(150, 600);
        cb.lineTo(150, 800);
        cb.moveTo(50, 760);
        cb.lineTo(250, 760);
        cb.moveTo(50, 700);
        cb.lineTo(250, 700);
        cb.moveTo(50, 640);
        cb.lineTo(250, 640);
        cb.stroke();
        // draw text
        String text = "AWAY again ";
        BaseFont bf = BaseFont.createFont();
        cb.beginText();
        cb.setFontAndSize(bf, 12);
        cb.setTextMatrix(50, 800);
        cb.showText(text);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text + " Center", 150, 760, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, text + " Right", 150, 700, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text + " Left", 150, 640, 0);
        cb.showTextAlignedKerned(PdfContentByte.ALIGN_LEFT, text + " Left", 150, 628, 0);
        cb.setTextMatrix(0, 1, -1, 0, 300, 600);
        cb.showText("Position 300,600, rotated 90 degrees.");
        for (int i = 0; i < 360; i += 30) {
            cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text, 400, 700, i);
        }
        cb.endText();
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new TextMethods().createPdf(RESULT);
    }

}
PearExample.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class PearExample extends JPanel {
    
    /** Ellipse in Double precision */
    Ellipse2D.Double circle;
    /** Ellipse in Double precision */
    Ellipse2D.Double oval;
    /** Ellipse in Double precision */
    Ellipse2D.Double leaf;
    /** Ellipse in Double precision */
    Ellipse2D.Double stem;

    /** A geometric area */
    Area circ;
    /** A geometric area */
    Area ov;
    /** A geometric area */
    Area leaf1;
    /** A geometric area */
    Area leaf2;
    /** A geometric area */
    Area st1;
    /** A geometric area */
    Area st2;

    /**
     * Initializes all the values needed to draw a Pear on a JPanel.
     */
    public PearExample() {
        circle = new Ellipse2D.Double();
        oval = new Ellipse2D.Double();
        leaf = new Ellipse2D.Double();
        stem = new Ellipse2D.Double();
        circ = new Area(circle);
        ov = new Area(oval);
        leaf1 = new Area(leaf);
        leaf2 = new Area(leaf);
        st1 = new Area(stem);
        st2 = new Area(stem);
    }
    
    /**
     * Paints a pear.
     * @see javax.swing.JComponent#paint(java.awt.Graphics)
     */
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        double ew = 75;
        double eh = 75;

        g2.setColor(Color.GREEN);

        // Creates the first leaf by filling the intersection of two Area
        // objects created from an ellipse.
        leaf.setFrame(ew - 16, eh - 29, 15.0, 15.0);
        leaf1 = new Area(leaf);
        leaf.setFrame(ew - 14, eh - 47, 30.0, 30.0);
        leaf2 = new Area(leaf);
        leaf1.intersect(leaf2);
        g2.fill(leaf1);

        // Creates the second leaf.
        leaf.setFrame(ew + 1, eh - 29, 15.0, 15.0);
        leaf1 = new Area(leaf);
        leaf2.intersect(leaf1);
        g2.fill(leaf2);

        g2.setColor(Color.BLACK);

        // Creates the stem by filling the Area resulting from the subtraction
        // of two Area objects created from an ellipse.
        stem.setFrame(ew, eh - 42, 40.0, 40.0);
        st1 = new Area(stem);
        stem.setFrame(ew + 3, eh - 47, 50.0, 50.0);
        st2 = new Area(stem);
        st1.subtract(st2);
        g2.fill(st1);

        g2.setColor(Color.YELLOW);

        // Creates the pear itself by filling the Area resulting from the union
        // of two Area objects created by two different ellipses.
        circle.setFrame(ew - 25, eh, 50.0, 50.0);
        oval.setFrame(ew - 19, eh - 20, 40.0, 70.0);
        circ = new Area(circle);
        ov = new Area(oval);
        circ.add(ov);
        g2.fill(circ);
    }
    
    /**
     * Opens a JFrame showing a Pear.
     * @param args no arguments needed
     */
    public static void main(String[] args) {
        PearExample pear = new PearExample();
        JFrame f = new JFrame("Pear");
        f.getContentPane().add( pear, "Center" );

        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        f.setSize(new Dimension(160, 200));
        f.setVisible(true);
    }

    /** A serial version UID. */
    private static final long serialVersionUID = 1251626928914650961L;
}
PearToPdf.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Graphics2D;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class PearToPdf {

    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/pear.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Document document = new Document(new Rectangle(150, 150));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        Graphics2D g2 = new PdfGraphics2D(canvas, 150, 150);
        PearExample pear = new PearExample();
        pear.paint(g2);
        g2.dispose();
        // step 5
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new PearToPdf().createPdf(RESULT);
    }
}
DirectorCharts.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.lowagie.database.DatabaseConnection;
import com.lowagie.database.HsqldbConnection;
import com.lowagie.filmfestival.Director;
import com.lowagie.filmfestival.PojoFactory;

public class DirectorCharts {
    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/director_charts.pdf";
    /** A query that needs to be visualized in a chart. */
    public static final String QUERY1 =
        "SELECT DISTINCT d.id, d.name, d.given_name, count(*) AS c "
            + "FROM film_director d, film_movie_director md "
            + "WHERE d.id = md.director_id "
            + "GROUP BY d.id, d.name, d.given_name ORDER BY c DESC, name LIMIT 9";
    /** A query that needs to be visualized in a chart. */
    public static final String QUERY2 =
        "SELECT DISTINCT d.id, d.name, d.given_name, count(*) AS c "
            + "FROM film_director d, film_movie_director md "
            + "WHERE d.id = md.director_id "
            + "GROUP BY d.id, d.name, d.given_name ORDER BY c DESC, name LIMIT 17";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     * @throws SQLException 
     */
    public void createPdf(String filename) throws IOException, DocumentException, SQLException {
    	// step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        float width = PageSize.A4.getWidth();
        float height = PageSize.A4.getHeight() / 2;
        // Pie chart
        PdfTemplate pie = cb.createTemplate(width, height);
        Graphics2D g2d1 = new PdfGraphics2D(pie, width, height);
        Rectangle2D r2d1 = new Rectangle2D.Double(0, 0, width, height);
        getPieChart().draw(g2d1, r2d1);
        g2d1.dispose();
        cb.addTemplate(pie, 0, height);
        // Bar chart
        PdfTemplate bar = cb.createTemplate(width, height);
        Graphics2D g2d2 = new PdfGraphics2D(bar, width, height);
        Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, width, height);
        getBarChart().draw(g2d2, r2d2);
        g2d2.dispose();
        cb.addTemplate(bar, 0, 0);
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     * @throws SQLException 
     */
    public static void main(String[] args) throws IOException, DocumentException, SQLException {
        new DirectorCharts().createPdf(RESULT);
    }
    
    /**
     * Gets an example pie chart.
     * 
     * @return a pie chart
     * @throws SQLException 
     * @throws IOException 
     */
    public static JFreeChart getPieChart() throws SQLException, IOException {
        DatabaseConnection connection = new HsqldbConnection("filmfestival");
        Statement stm = connection.createStatement();
        ResultSet rs = stm.executeQuery(QUERY1);
        DefaultPieDataset dataset = new DefaultPieDataset();
        Director director;
        while (rs.next()) {
            director = PojoFactory.getDirector(rs);
            dataset.setValue(
                String.format("%s, %s", director.getName(), director.getGivenName()),
                rs.getInt("c"));
        }
        connection.close();
        return ChartFactory.createPieChart("Movies / directors", dataset,
                true, true, false);
    }
    
    /**
     * Gets an example bar chart.
     * 
     * @return a bar chart
     * @throws SQLException 
     * @throws IOException 
     */
    public static JFreeChart getBarChart() throws SQLException, IOException {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        DatabaseConnection connection = new HsqldbConnection("filmfestival");
        Statement stm = connection.createStatement();
        ResultSet rs = stm.executeQuery(QUERY2);
        Director director;
        while (rs.next()) {
            director = PojoFactory.getDirector(rs);
            dataset.setValue(
                rs.getInt("c"),
                "movies",
                String.format("%s, %s", director.getName(), director.getGivenName()));
        }
        connection.close();
        return ChartFactory.createBarChart("Movies / directors", "Director",
                "# Movies", dataset, PlotOrientation.HORIZONTAL, false,
                true, false);
    }
}
Graphics2DFonts.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Map.Entry;

import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.awt.DefaultFontMapper.BaseFontParameters;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class Graphics2DFonts {
    /** A text file containing the available AWT fonts. */
    public static final String RESULT1
        = "results/part4/chapter14/awt_fonts.txt";
    /** A text file containing the mapping of PDF and AWT fonts. */
    public static final String RESULT2
        = "results/part4/chapter14/pdf_fonts.txt";
    /** The resulting PDF. */
    public static final String RESULT3
        = "results/part4/chapter14/fonts.pdf";
    
    /** A series of fonts that will be used. */
    public static final Font[] FONTS = {
        new Font("Serif", Font.PLAIN, 12),
        new Font("Serif", Font.BOLD, 12),
        new Font("Serif", Font.ITALIC, 12),
        new Font("SansSerif", Font.PLAIN, 12),
        new Font("Monospaced", Font.PLAIN, 12)
    };

    /**
     * Creates lists of fonts that can be used in AWT and PDF.
     * Creates a PDF document.
     * @param args no arguments needed
     * @throws IOException
     * @throws DocumentException
     */
    public static void main(String[] args) throws IOException, DocumentException {
    	// Creates a list of the available font families in Java AWT.
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontFamily = ge.getAvailableFontFamilyNames();
        PrintStream out1 = new PrintStream(new FileOutputStream(RESULT1));
        for (int i = 0; i < fontFamily.length; i++) {
            out1.println(fontFamily[i]);
        }
        out1.flush();
        out1.close();
        
        // Creates a mapper to map fonts available for PDF creation with AWT fonts
        DefaultFontMapper mapper = new DefaultFontMapper();
        mapper.insertDirectory("c:/windows/fonts/");
        // Writes a text version of this mapper to a file
        PrintStream out2 = new PrintStream(new FileOutputStream(RESULT2));
        for (Entry entry : mapper.getMapper().entrySet()) {
            out2.println(String.format("%s: %s", entry.getKey(), entry.getValue().fontName));
        }
        out2.flush();
        out2.close();
        
        // Creates a PDF with the text "Hello World" in different fonts.
        float width = 150;
        float height = 150;
        // step 1
        Document document = new Document(new Rectangle(width, height));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT3));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g2d = new PdfGraphics2D(cb, width, height, mapper);
        for (int i = 0; i < FONTS.length; ) {
            g2d.setFont(FONTS[i++]);
            g2d.drawString("Hello world", 5, 24 * i);
        }
        g2d.dispose();
        // step 5
        document.close();
    }
}
TextExample1.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.AttributedString;
import java.awt.font.TextAttribute;


import javax.swing.JFrame;
import javax.swing.JPanel;

public class TextExample1 extends JPanel {

    /** A String that needs to be displayed in a PDF document */
    private static AttributedString akira;

    /**
     * Creates a TextExample that will be used to demonstrate how text in AWT can be translated to PDF.
     */
    public TextExample1() {
        akira = new AttributedString(
            "Akira Kurosawa: \u9ed2\u6fa4 \u660e or \u9ed2\u6ca2 \u660e; " +
            "23 March 1910 - 6 September 1998.");
        akira.addAttribute(TextAttribute.FONT, new Font("SansSerif", Font.PLAIN, 12));
        akira.addAttribute(TextAttribute.FONT, new Font("SansSerif", Font.BOLD, 12), 0, 15);
        akira.addAttribute(TextAttribute.FONT, new Font("MS PGothic", Font.PLAIN, 12), 16, 20);
        akira.addAttribute(TextAttribute.FONT, new Font("MS PGothic", Font.PLAIN, 12), 24, 28);
    }

    /**
     * Draws the String to a Graphics object.
     * @see javax.swing.JComponent#paint(java.awt.Graphics)
     */
    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawString(akira.getIterator(), 10, 16);
    }
    
    /**
     * Creates a JFrame and draws a String to it.
     * @param args no arguments needed
     */
    public static void main(String[] args) {
        TextExample1 Kurosawa = new TextExample1();
        JFrame f = new JFrame("Kurosawa");
        f.getContentPane().add( Kurosawa, "Center" );
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        f.setSize(new Dimension(500, 60));
        f.setVisible(true);
    }

    /** A serial version UID */
    private static final long serialVersionUID = -3639324875232824761L;
}
Text1ToPdf1.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Graphics2D;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class Text1ToPdf1 {
    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/text11.pdf";

    /**
     * Creates a PDF document.
     * This example doesn't work as expected.
     * See Text1ToPdf2 to find out how to do it correctly.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Document document = new Document(new Rectangle(600, 60));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        // Create a font mapper and add a font directory
        DefaultFontMapper mapper = new DefaultFontMapper();
        mapper.insertDirectory("c:/windows/fonts/");
        // create the Graphics2D object
        Graphics2D g2 = new PdfGraphics2D(canvas, 600, 60, mapper);
        // write the text to the Graphics2D (will NOT work as expected!)
        TextExample1 text = new TextExample1();
        text.paint(g2);
        g2.dispose();
        // step 5
        document.close();
    }
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Text1ToPdf1().createPdf(RESULT);
    }
}
Text1ToPdf2.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Graphics2D;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.awt.DefaultFontMapper.BaseFontParameters;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class Text1ToPdf2 {
    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/text12.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Document document = new Document(new Rectangle(600, 60));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        // create a font mapper
        DefaultFontMapper mapper = new DefaultFontMapper();
        // map MS Gothic to the corresponding font program
        BaseFontParameters parameters = new BaseFontParameters("c:/windows/fonts/msgothic.ttc,1");
        parameters.encoding = BaseFont.IDENTITY_H;
        mapper.putName("MS PGothic", parameters );
        // Create a Graphics2D object
        Graphics2D g2 = new PdfGraphics2D(canvas, 600, 60, mapper);
        // write the text to the Graphics2D
        TextExample1 text = new TextExample1();
        text.paint(g2);
        g2.dispose();
        // step 5
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Text1ToPdf2().createPdf(RESULT);
    }
}
TextExample2.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;


import javax.swing.JFrame;
import javax.swing.JPanel;

public class TextExample2 extends JPanel {

    /** A String that needs to be displayed in a PDF document */
    private static AttributedString akira;

    /** A String that needs to be displayed in a PDF document */
    public static final String AKIRA =
        "Akira Kurosawa (\u9ed2\u6fa4 \u660e or \u9ed2\u6ca2 \u660e, " +
        "Kurosawa Akira, 23 March 1910 - 6 September 1998) was a " +
        "Japanese film director, producer, screenwriter and editor. " +
        "In a career that spanned 50 years, Kurosawa directed 30 films. " +
        "He is widely regarded as one of the most important and " +
        "influential filmmakers in film history.";

    /**
     * Creates a TextExample that will be used to demonstrate how text in AWT can be translated to PDF.
     */
    public TextExample2() {
        akira = new AttributedString(AKIRA);
        akira.addAttribute(TextAttribute.FONT, new Font("Arial Unicode MS", Font.PLAIN, 12));
    }

    /**
     * Draws the String to a Graphics object.
     * @see javax.swing.JComponent#paint(java.awt.Graphics)
     */
    public void paint(Graphics g) {
    	LineBreakMeasurer lineMeasurer = null;
    	int paragraphStart = 0;
    	int paragraphEnd = 0;
        Graphics2D g2d = (Graphics2D) g;
        g2d.setFont(new Font("Arial Unicode MS", Font.PLAIN, 12));
        if (lineMeasurer == null) {
            AttributedCharacterIterator paragraph = akira.getIterator();
            paragraphStart = paragraph.getBeginIndex();
            paragraphEnd = paragraph.getEndIndex();
            FontRenderContext frc = g2d.getFontRenderContext();
            lineMeasurer = new LineBreakMeasurer(paragraph, frc);
        }
        float breakWidth = (float)getSize().width;
        float drawPosY = 0;
        lineMeasurer.setPosition(paragraphStart);
        int start = 0;
        int end = 0;
        while (lineMeasurer.getPosition() < paragraphEnd) {
            TextLayout layout = lineMeasurer.nextLayout(breakWidth);
            drawPosY += layout.getAscent();
            end = start + layout.getCharacterCount();
            g2d.drawString(AKIRA.substring(start, end), 0, drawPosY);
            start = end;
            drawPosY += layout.getDescent() + layout.getLeading();
        }
    }
    
    /**
     * Creates a JFrame and draws a String to it.
     * @param args no arguments needed
     */
    public static void main(String[] args) {
        TextExample2 Kurosawa = new TextExample2();
        JFrame f = new JFrame("Kurosawa");
        f.getContentPane().add( Kurosawa, "Center" );

        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        f.setSize(new Dimension(300, 150));
        f.setVisible(true);
    }

    /** A serial version UID. */
    private static final long serialVersionUID = -3639324875232824761L;
}
Text2ToPdf1.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.awt.FontMapper;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class Text2ToPdf1 {
    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/text21.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Document document = new Document(new Rectangle(300, 150));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        // Create a custom font mapper that forces the use of arial unicode
        FontMapper arialuni = new FontMapper() {
            public BaseFont awtToPdf(Font font) {
                try {
                    return BaseFont.createFont(
                            "c:/windows/fonts/arialuni.ttf",
                            BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            public Font pdfToAwt(BaseFont font, int size) {
                return null;
            }
            
        };
        // Create a Graphics2D object
        Graphics2D g2 = new PdfGraphics2D(canvas, 300, 150, arialuni);
        // Draw text to the Graphics2D
        TextExample2 text = new TextExample2();
        text.setSize(new Dimension(300, 150));
        text.paint(g2);
        g2.dispose();
        // step 5
        document.close();
    }
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Text2ToPdf1().createPdf(RESULT);
    }
}
Text2ToPdf2.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.awt.AsianFontMapper;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class Text2ToPdf2 {
    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/text22.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Document document = new Document(new Rectangle(300, 150));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        Graphics2D g2 = new PdfGraphics2D(canvas, 300, 150, new AsianFontMapper(
                AsianFontMapper.JapaneseFont_Min, AsianFontMapper.JapaneseEncoding_H));
        TextExample2 text = new TextExample2();
        text.setSize(new Dimension(300, 150));
        text.paint(g2);
        g2.dispose();
        // step 5
        document.close();
    }
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Text2ToPdf2().createPdf(RESULT);
    }
}
Text2ToPdf3.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class Text2ToPdf3 {
    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/text23.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Document document = new Document(new Rectangle(300, 150));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        Graphics2D g2 = new PdfGraphics2D(canvas, 300, 150, true);
        TextExample2 text = new TextExample2();
        text.setSize(new Dimension(300, 150));
        text.paint(g2);
        g2.dispose();
        // step 5
        document.close();
    }
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Text2ToPdf3().createPdf(RESULT);
    }
}
TextExample3.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;


import javax.swing.JFrame;
import javax.swing.JPanel;

public class TextExample3 extends JPanel {

    /** A String that needs to be displayed in a PDF document */
    private static AttributedString akira;

    /**
     * Creates a TextExample that will be used to demonstrate how text in AWT can be translated to PDF.
     */
    public TextExample3() {
        akira = new AttributedString(
            "Akira Kurosawa (\u9ed2\u6fa4 \u660e or \u9ed2\u6ca2 \u660e, " +
            "Kurosawa Akira, 23 March 1910 - 6 September 1998) was a " +
            "Japanese film director, producer, screenwriter and editor. " +
            "In a career that spanned 50 years, Kurosawa directed 30 films. " +
            "He is widely regarded as one of the most important and " +
            "influential filmmakers in film history.");
        akira.addAttribute(TextAttribute.FONT, new Font("SansSerif", Font.PLAIN, 12));
        akira.addAttribute(TextAttribute.FONT, new Font("SansSerif", Font.BOLD, 12), 0, 14);
        akira.addAttribute(TextAttribute.FONT, new Font("MS PGothic", Font.PLAIN, 12), 16, 20);
        akira.addAttribute(TextAttribute.FONT, new Font("MS PGothic", Font.PLAIN, 12), 24, 28);
    }

    /**
     * Draws the String to a Graphics object.
     * @see javax.swing.JComponent#paint(java.awt.Graphics)
     */
    public void paint(Graphics g) {
    	LineBreakMeasurer lineMeasurer = null;
    	int paragraphStart = 0;
    	int paragraphEnd = 0;
        Graphics2D g2d = (Graphics2D) g;
        if (lineMeasurer == null) {
            AttributedCharacterIterator paragraph = akira.getIterator();
            paragraphStart = paragraph.getBeginIndex();
            paragraphEnd = paragraph.getEndIndex();
            FontRenderContext frc = g2d.getFontRenderContext();
            lineMeasurer = new LineBreakMeasurer(paragraph, frc);
        }
        float breakWidth = (float)getSize().width;
        float drawPosY = 0;
        lineMeasurer.setPosition(paragraphStart);
        while (lineMeasurer.getPosition() < paragraphEnd) {
            TextLayout layout = lineMeasurer.nextLayout(breakWidth);
            drawPosY += layout.getAscent();
            layout.draw(g2d, 0, drawPosY);
            drawPosY += layout.getDescent() + layout.getLeading();
        }
    }
    
    /**
     * Creates a JFrame and draws a String to it.
     * @param args no arguments needed
     */
    public static void main(String[] args) {
        TextExample3 Kurosawa = new TextExample3();
        JFrame f = new JFrame("Kurosawa");
        f.getContentPane().add( Kurosawa, "Center" );

        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        f.setSize(new Dimension(300, 150));
        f.setVisible(true);
    }

    /** A serial version UID. */
    private static final long serialVersionUID = -3639324875232824761L;
}
Text3ToPdf.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class Text3ToPdf {
    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/text3.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Document document = new Document(new Rectangle(300, 150));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        Graphics2D g2 = new PdfGraphics2D(canvas, 300, 150);
        TextExample3 text = new TextExample3();
        text.setSize(new Dimension(300, 150));
        text.paint(g2);
        g2.dispose();
        // step 5
        document.close();
    }
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Text3ToPdf().createPdf(RESULT);
    }
}
TextExample4.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

public class TextExample4 {

    /** A String that needs to be displayed in a PDF document */
    public static final String[] AKIRA = {
        "Akira Kurosawa", " (", "\u9ed2\u6fa4 \u660e", " or ",
        "\u9ed2\u6ca2 \u660e", ", Kurosawa Akira, 23 March 1910" +
        " - 6 September 1998) was a Japanese film director," +
        " producer, screenwriter and editor. In a career that" +
        " spanned 50 years, Kurosawa directed 30 films. " +
        "He is widely regarded as one of the most important and " +
        "influential filmmakers in film history." };

    /** Styles that will be used in the AKIRA String. */
    public static final String[] STYLES =  {
      "bold", "regular", "japanese", "regular", "japanese", "regular" };
    
    /**
     * Creates a JTextPane with the String we want to display in a PDF document.
     * @return a JTextPane
     * @throws BadLocationException
     */
    public static JTextPane createTextPane() throws BadLocationException {
        JTextPane textPane = new JTextPane();
        StyledDocument doc = textPane.getStyledDocument();
        initStyles(doc);
        for (int i=0; i < AKIRA.length; i++) {
            doc.insertString(doc.getLength(), AKIRA[i],
            doc.getStyle(STYLES[i]));
        }
        return textPane;
    }

    /**
     * Initialization of the styles that are used in the String.
     * @param doc    a StyledDocument
     */
    public static void initStyles(StyledDocument doc) {
        Style def =
            StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
        StyleConstants.setFontFamily(def, "SansSerif");
        Style regular = doc.addStyle("regular", def);
        Style bold = doc.addStyle("bold", regular);
        StyleConstants.setBold(bold, true);
        Style japanese = doc.addStyle("japanese", def);
        StyleConstants.setFontFamily(japanese, "MS PGothic");
    }
    
    /**
     * Creates a JFrame and draws a String to it.
     * @param args no arguments needed
     * @throws BadLocationException
     */
    public static void main(String[] args) throws BadLocationException {
        JFrame f = new JFrame("Kurosawa");
        f.getContentPane().add( createTextPane(), "Center" );

        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        f.setSize(new Dimension(300, 150));
        f.setVisible(true);
    }

}
Text4ToPdf.java
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part4.chapter14;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;

import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.awt.DefaultFontMapper.BaseFontParameters;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class Text4ToPdf {

    /** The resulting PDF. */
    public static final String RESULT = "results/part4/chapter14/text4.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException
     * @throws BadLocationException 
     */
    public void createPdf(String filename) throws IOException, DocumentException, BadLocationException {
    	// step 1
        Document document = new Document(new Rectangle(300, 150));
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContent();
        // create a default font mapper
        DefaultFontMapper mapper = new DefaultFontMapper();
        // and map MS Gothic to the corresponding font program
        BaseFontParameters parameters = new BaseFontParameters("c:/windows/fonts/msgothic.ttc,1");
        parameters.encoding = BaseFont.IDENTITY_H;
        mapper.putName("MS PGothic", parameters );
        Graphics2D g2 = new PdfGraphics2D(canvas, 300, 150, mapper);
        // create the text pane and print it.
        JTextPane text = TextExample4.createTextPane();
        text.setSize(new Dimension(300, 150));
        text.print(g2);
        g2.dispose();
        // step 5
        document.close();
    }
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     * @throws BadLocationException 
     */
    public static void main(String[] args) throws IOException, DocumentException, BadLocationException {
        new Text4ToPdf().createPdf(RESULT);
    }
}
GetContentStream.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ionic.Zip;
using iTextSharp.text;
using iTextSharp.text.pdf;
using kuujinbo.iTextInAction2Ed.Chapter01;
using kuujinbo.iTextInAction2Ed.Chapter05;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class GetContentStream : IWriter {
// ===========================================================================
    /** The content stream of a first PDF. */
    public const String RESULT1 = "contentstream1.txt";
    /** The content stream of a second PDF. */
    public const String RESULT2 = "contentstream2.txt";
// ---------------------------------------------------------------------------    
    public void Write(Stream stream) {
      HelloWorld hello = new HelloWorld();
      Hero1 hero = new Hero1();
      using (ZipFile zip = new ZipFile()) {
        byte[] pdfHello = Utility.PdfBytes(hello);
        byte[] pdfHero = Utility.PdfBytes(hero);
        zip.AddEntry(Utility.ResultFileName(
          hello.ToString() + ".pdf"), pdfHello
        );       
        zip.AddEntry(Utility.ResultFileName(
          hero.ToString() + ".pdf"), pdfHero
        );
        GetContentStream example = new GetContentStream();
        zip.AddEntry(RESULT1, example.ReadContent(pdfHello));
        zip.AddEntry(RESULT2, example.ReadContent(pdfHero));
        zip.Save(stream);             
      }    
    }
// ---------------------------------------------------------------------------    
    /**
     * Reads the content stream of the first page of a PDF into a text file.
     * @param src the PDF file
     */
    public string ReadContent(byte[] src) {
      PdfReader reader = new PdfReader(src);
      byte[] pc = reader.GetPageContent(1);
      return Encoding.UTF8.GetString(pc, 0, pc.Length);
    }
// ===========================================================================
  }
}
PathConstructionAndPainting.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class PathConstructionAndPainting : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte canvas = writer.DirectContent;
        // draw squares
        CreateSquares(canvas, 50, 720, 80, 20);
        ColumnText.ShowTextAligned(
          canvas, Element.ALIGN_LEFT,
          new Phrase(
            "Methods MoveTo(), LineTo(), stroke(), closePathStroke(), Fill(), and closePathFill()"
          ),
          50, 700, 0
        );
        // draw Bezier curves
        createBezierCurves(canvas, 70, 600, 80, 670, 140, 690, 160, 630, 160);
        ColumnText.ShowTextAligned(
          canvas, Element.ALIGN_LEFT,
          new Phrase("Different CurveTo() methods, followed by stroke()"),
          50, 580, 0
        );
        // draw stars and circles
        CreateStarsAndCircles(canvas, 50, 470, 40, 20);
        ColumnText.ShowTextAligned(
          canvas, Element.ALIGN_LEFT,
          new Phrase(
            "Methods Fill(), eoFill(), NewPath(), FillStroke(), and EoFillStroke()"
          ),
          50, 450, 0
        );
        // draw different shapes using convenience methods
        canvas.SaveState();
        canvas.SetColorStroke(new GrayColor(0.2f));
        canvas.SetColorFill(new GrayColor(0.9f));
        canvas.Arc(50, 270, 150, 330, 45, 270);
        canvas.Ellipse(170, 270, 270, 330);
        canvas.Circle(320, 300, 30);
        canvas.RoundRectangle(370, 270, 80, 60, 20);
        canvas.FillStroke();
        canvas.RestoreState();
        Rectangle rect = new Rectangle(470, 270, 550, 330);
        rect.BorderWidthBottom = 10;
        rect.BorderColorBottom = new GrayColor(0f);
        rect.BorderWidthLeft = 4;
        rect.BorderColorLeft = new GrayColor(0.9f);
        rect.BackgroundColor = new GrayColor(0.4f);
        canvas.Rectangle(rect);
        ColumnText.ShowTextAligned(
          canvas, Element.ALIGN_LEFT,
          new Phrase("Convenience methods"), 50, 250, 0
        );
      }
    }
// ---------------------------------------------------------------------------    
    /**
     * Draws a row of squares.
     * @param canvas the canvas to which the squares have to be drawn
     * @param x      X coordinate to position the row
     * @param y      Y coordinate to position the row
     * @param side   the side of the square
     * @param gutter the space between the squares
     */
    public void CreateSquares(PdfContentByte canvas,
      float x, float y, float side, float gutter) {
      canvas.SaveState();
      canvas.SetColorStroke(new GrayColor(0.2f));
      canvas.SetColorFill(new GrayColor(0.9f));
      canvas.MoveTo(x, y);
      canvas.LineTo(x + side, y);
      canvas.LineTo(x + side, y + side);
      canvas.LineTo(x, y + side);
      canvas.Stroke();
      x = x + side + gutter;
      canvas.MoveTo(x, y);
      canvas.LineTo(x + side, y);
      canvas.LineTo(x + side, y + side);
      canvas.LineTo(x, y + side);
      canvas.ClosePathStroke();
      x = x + side + gutter;
      canvas.MoveTo(x, y);
      canvas.LineTo(x + side, y);
      canvas.LineTo(x + side, y + side);
      canvas.LineTo(x, y + side);
      canvas.Fill();
      x = x + side + gutter;
      canvas.MoveTo(x, y);
      canvas.LineTo(x + side, y);
      canvas.LineTo(x + side, y + side);
      canvas.LineTo(x, y + side);
      canvas.FillStroke();
      x = x + side + gutter;
      canvas.MoveTo(x, y);
      canvas.LineTo(x + side, y);
      canvas.LineTo(x + side, y + side);
      canvas.LineTo(x, y + side);
      canvas.ClosePathFillStroke();
      canvas.RestoreState();
    }
// ---------------------------------------------------------------------------    
    /**
     * Draws a series of Bezier curves
     * @param cb the canvas to which the curves have to be drawn
     * @param x0 X coordinate of the start point
     * @param y0 Y coordinate of the start point
     * @param x1 X coordinate of the first control point
     * @param y1 Y coordinate of the first control point
     * @param x2 X coordinate of the second control point
     * @param y2 Y coordinate of the second control point
     * @param x3 X coordinate of the end point
     * @param y3 Y coordinate of the end point
     * @param distance the distance between the curves
     */
    public void createBezierCurves(PdfContentByte cb, float x0, float y0,
        float x1, float y1, float x2, float y2, float x3, 
        float y3, float distance) 
    {
      cb.MoveTo(x0, y0);
      cb.LineTo(x1, y1);
      cb.MoveTo(x2, y2);
      cb.LineTo(x3, y3);
      cb.MoveTo(x0, y0);
      cb.CurveTo(x1, y1, x2, y2, x3, y3);
      x0 += distance;
      x1 += distance;
      x2 += distance;
      x3 += distance;
      cb.MoveTo(x2, y2);
      cb.LineTo(x3, y3);
      cb.MoveTo(x0, y0);
      cb.CurveTo(x2, y2, x3, y3);
      x0 += distance;
      x1 += distance;
      x2 += distance;
      x3 += distance;
      cb.MoveTo(x0, y0);
      cb.LineTo(x1, y1);
      cb.MoveTo(x0, y0);
      cb.CurveTo(x1, y1, x3, y3);
      cb.Stroke();
    }
// ---------------------------------------------------------------------------    
    /**
     * Draws a row of stars and circles.
     * @param canvas the canvas to which the shapes have to be drawn
     * @param x      X coordinate to position the row
     * @param y      Y coordinate to position the row
     * @param radius the radius of the circles
     * @param gutter the space between the shapes
     */
    public static void CreateStarsAndCircles(PdfContentByte canvas,
        float x, float y, float radius, float gutter) 
    {
      canvas.SaveState();
      canvas.SetColorStroke(new GrayColor(0.2f));
      canvas.SetColorFill(new GrayColor(0.9f));
      CreateStar(canvas, x, y);
      CreateCircle(canvas, x + radius, y - 70, radius, true);
      CreateCircle(canvas, x + radius, y - 70, radius / 2, true);
      canvas.Fill();
      x += 2 * radius + gutter;
      CreateStar(canvas, x, y);
      CreateCircle(canvas, x + radius, y - 70, radius, true);
      CreateCircle(canvas, x + radius, y - 70, radius / 2, true);
      canvas.EoFill();
      x += 2 * radius + gutter;
      CreateStar(canvas, x, y);
      canvas.NewPath();
      CreateCircle(canvas, x + radius, y - 70, radius, true);
      CreateCircle(canvas, x + radius, y - 70, radius / 2, true);
      x += 2 * radius + gutter;
      CreateStar(canvas, x, y);
      CreateCircle(canvas, x + radius, y - 70, radius, true);
      CreateCircle(canvas, x + radius, y - 70, radius / 2, false);
      canvas.FillStroke();
      x += 2 * radius + gutter;
      CreateStar(canvas, x, y);
      CreateCircle(canvas, x + radius, y - 70, radius, true);
      CreateCircle(canvas, x + radius, y - 70, radius / 2, true);
      canvas.EoFillStroke();
      canvas.RestoreState();
    }
// ---------------------------------------------------------------------------    
    /**
     * Creates a path for a five pointed star.
     * This method doesn't fill or stroke the star!
     * @param canvas the canvas for which the star is constructed
     * @param x      the X coordinate of the center of the star
     * @param y      the Y coordinate of the center of the star
     */
    public static void CreateStar(PdfContentByte canvas, float x, float y) {
      canvas.MoveTo(x + 10, y);
      canvas.LineTo(x + 80, y + 60);
      canvas.LineTo(x, y + 60);
      canvas.LineTo(x + 70, y);
      canvas.LineTo(x + 40, y + 90);
      canvas.ClosePath();
    }
// --------------------------------------------------------------------------- 
    /**
     * Creates a path for circle using Bezier curvers.
     * The path can be constructed clockwise or counter-clockwise.
     * This method doesn't Fill or stroke the circle!
     * @param canvas    the canvas for which the path is constructed 
     * @param x         the X coordinate of the center of the circle
     * @param y         the Y coordinate of the center of the circle
     * @param r         the radius
     * @param clockwise true if the circle has to be constructed clockwise
     */
    public static void CreateCircle(PdfContentByte canvas, float x, float y,
      float r, bool clockwise) 
    {
      float b = 0.5523f;
      if (clockwise) {
        canvas.MoveTo(x + r, y);
        canvas.CurveTo(x + r, y - r * b, x + r * b, y - r, x, y - r);
        canvas.CurveTo(x - r * b, y - r, x - r, y - r * b, x - r, y);
        canvas.CurveTo(x - r, y + r * b, x - r * b, y + r, x, y + r);
        canvas.CurveTo(x + r * b, y + r, x + r, y + r * b, x + r, y);
      } else {
        canvas.MoveTo(x + r, y);
        canvas.CurveTo(x + r, y + r * b, x + r * b, y + r, x, y + r);
        canvas.CurveTo(x - r * b, y + r, x - r, y + r * b, x - r, y);
        canvas.CurveTo(x - r, y - r * b, x - r * b, y - r, x, y - r);
        canvas.CurveTo(x + r * b, y - r, x + r, y - r * b, x + r, y);
      }
    }    
// ===========================================================================
  }
}
GraphicsStateOperators.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class GraphicsStateOperators : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte canvas = writer.DirectContent;
        // line widths
        canvas.SaveState();
        for (int i = 25; i > 0; i--) {
          canvas.SetLineWidth((float) i / 10);
          canvas.MoveTo(50, 806 - (5 * i));
          canvas.LineTo(320, 806 - (5 * i));
          canvas.Stroke();
        }
        canvas.RestoreState();
        
        // line cap
        canvas.MoveTo(350, 800);
        canvas.LineTo(350, 750);
        canvas.MoveTo(540, 800);
        canvas.LineTo(540, 750);
        canvas.Stroke();
        
        canvas.SaveState();
        canvas.SetLineWidth(8);
        canvas.SetLineCap(PdfContentByte.LINE_CAP_BUTT);
        canvas.MoveTo(350, 790);
        canvas.LineTo(540, 790);
        canvas.Stroke();
        canvas.SetLineCap(PdfContentByte.LINE_CAP_ROUND);
        canvas.MoveTo(350, 775);
        canvas.LineTo(540, 775);
        canvas.Stroke();
        canvas.SetLineCap(PdfContentByte.LINE_CAP_PROJECTING_SQUARE);
        canvas.MoveTo(350, 760);
        canvas.LineTo(540, 760);
        canvas.Stroke();
        canvas.RestoreState();
        
        // join miter
        canvas.SaveState();
        canvas.SetLineWidth(8);
        canvas.SetLineJoin(PdfContentByte.LINE_JOIN_MITER);
        canvas.MoveTo(387, 700);
        canvas.LineTo(402, 730);
        canvas.LineTo(417, 700);
        canvas.Stroke();
        canvas.SetLineJoin(PdfContentByte.LINE_JOIN_ROUND);
        canvas.MoveTo(427, 700);
        canvas.LineTo(442, 730);
        canvas.LineTo(457, 700);
        canvas.Stroke();
        canvas.SetLineJoin(PdfContentByte.LINE_JOIN_BEVEL);
        canvas.MoveTo(467, 700);
        canvas.LineTo(482, 730);
        canvas.LineTo(497, 700);
        canvas.Stroke();
        canvas.RestoreState();

        // line dash
        canvas.SaveState();
        canvas.SetLineWidth(3);
        canvas.MoveTo(50, 660);
        canvas.LineTo(320, 660);
        canvas.Stroke();
        canvas.SetLineDash(6, 0);
        canvas.MoveTo(50, 650);
        canvas.LineTo(320, 650);
        canvas.Stroke();
        canvas.SetLineDash(6, 3);
        canvas.MoveTo(50, 640);
        canvas.LineTo(320, 640);
        canvas.Stroke();
        canvas.SetLineDash(15, 10, 5);
        canvas.MoveTo(50, 630);
        canvas.LineTo(320, 630);
        canvas.Stroke();
        float[] dash1 = { 10, 5, 5, 5, 20 };
        canvas.SetLineDash(dash1, 5);
        canvas.MoveTo(50, 620);
        canvas.LineTo(320, 620);
        canvas.Stroke();
        float[] dash2 = { 9, 6, 0, 6 };
        canvas.SetLineCap(PdfContentByte.LINE_CAP_ROUND);
        canvas.SetLineDash(dash2, 0);
        canvas.MoveTo(50, 610);
        canvas.LineTo(320, 610);
        canvas.Stroke();
        canvas.RestoreState();

        // miter limit
        PdfTemplate hooks = canvas.CreateTemplate(300, 120);
        hooks.SetLineWidth(8);
        hooks.MoveTo(46, 50);
        hooks.LineTo(65, 80);
        hooks.LineTo(84, 50);
        hooks.Stroke();
        hooks.MoveTo(87, 50);
        hooks.LineTo(105, 80);
        hooks.LineTo(123, 50);
        hooks.Stroke();
        hooks.MoveTo(128, 50);
        hooks.LineTo(145, 80);
        hooks.LineTo(162, 50);
        hooks.Stroke();
        hooks.MoveTo(169, 50);
        hooks.LineTo(185, 80);
        hooks.LineTo(201, 50);
        hooks.Stroke();
        hooks.MoveTo(210, 50);
        hooks.LineTo(225, 80);
        hooks.LineTo(240, 50);
        hooks.Stroke();
        
        canvas.SaveState();
        canvas.SetMiterLimit(2);
        canvas.AddTemplate(hooks, 300, 600);
        canvas.RestoreState();
        
        canvas.SaveState();
        canvas.SetMiterLimit(2.1f);
        canvas.AddTemplate(hooks, 300, 550);
        canvas.RestoreState();
      }
    }
// ===========================================================================
  }
}
TransformationMatrix1.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.Com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Ionic.Zip;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class TransformationMatrix1 : IWriter {
// ===========================================================================
    /** The resulting PDF. */
    public const String RESULT = "transformation_matrix1.pdf";
    /** A PDF with the iText logo that will be transformed. */
    public readonly string RESOURCE = Path.Combine(
      Utility.ResourcePdf, "logo.pdf"
    );
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        TransformationMatrix1 t = new TransformationMatrix1();
        zip.AddFile(RESOURCE, "");       
        zip.AddEntry(RESULT, t.CreatePdf());
        zip.Save(stream);             
      }
    }
// ---------------------------------------------------------------------------
    /**
     * Creates a PDF document.
     */
    public byte[] CreatePdf() {
      // step 1
      Rectangle rect = new Rectangle(-595, -842, 595, 842);
      using (MemoryStream ms = new MemoryStream()) {
        using (Document document = new Document(rect)) {
          // step 2
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          PdfContentByte canvas = writer.DirectContent;
          canvas.MoveTo(-595, 0);
          canvas.LineTo(595, 0);
          canvas.MoveTo(0, -842);
          canvas.LineTo(0, 842);
          canvas.Stroke();
          // Read the PDF containing the logo
          PdfReader reader = new PdfReader(RESOURCE);
          PdfTemplate template = writer.GetImportedPage(reader, 1);
          // add it at different positions using different transformations
          canvas.SaveState();
          canvas.AddTemplate(template, 0, 0);
          canvas.ConcatCTM(0.5f, 0, 0, 0.5f, -595, 0);
          canvas.AddTemplate(template, 0, 0);
          canvas.ConcatCTM(1, 0, 0, 1, 595, 595);
          canvas.AddTemplate(template, 0, 0);
          canvas.RestoreState();

          canvas.SaveState();
          canvas.ConcatCTM(1, 0, 0.4f, 1, -750, -650);
          canvas.AddTemplate(template, 0, 0);
          canvas.RestoreState();
          
          canvas.SaveState();
          canvas.ConcatCTM(0, -1, -1, 0, 650, 0);
          canvas.AddTemplate(template, 0, 0);
          canvas.ConcatCTM(0.2f, 0, 0, 0.5f, 0, 300);
          canvas.AddTemplate(template, 0, 0);
          canvas.RestoreState();
        }
        return ms.ToArray();
      }
    }
// ===========================================================================
  }
}
TransformationMatrix2.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Ionic.Zip;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class TransformationMatrix2 : IWriter {
// ===========================================================================
    /** The resulting PDF. */
    public const String RESULT = "transformation_matrix2.pdf";
    /** A PDF with the iText logo that will be transformed. */
    public readonly string RESOURCE = Path.Combine(
      Utility.ResourcePdf, "logo.pdf"
    );
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        TransformationMatrix2 t = new TransformationMatrix2();
        zip.AddFile(RESOURCE, "");       
        zip.AddEntry(RESULT, t.CreatePdf());
        zip.Save(stream);             
      }
    }    
// ---------------------------------------------------------------------------
    /**
     * Creates a PDF document.
     */
    public byte[] CreatePdf() {
      Rectangle rect = new Rectangle(-595, -842, 595, 842);
      using (MemoryStream ms = new MemoryStream()) {
        using (Document document = new Document(rect)) {
          // step 2
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          PdfContentByte canvas = writer.DirectContent;
          canvas.MoveTo(-595, 0);
          canvas.LineTo(595, 0);
          canvas.MoveTo(0, -842);
          canvas.LineTo(0, 842);
          canvas.Stroke();
          
          // read the PDF with the logo
          PdfReader reader = new PdfReader(RESOURCE);
          PdfTemplate template = writer.GetImportedPage(reader, 1);
          // add it at different positions using different transformations 
          canvas.AddTemplate(template, 0, 0);
          canvas.AddTemplate(template, 0.5f, 0, 0, 0.5f, -595, 0);
          canvas.AddTemplate(template, 0.5f, 0, 0, 0.5f, -297.5f, 297.5f);
          canvas.AddTemplate(template, 1, 0, 0.4f, 1, -750, -650);
          canvas.AddTemplate(template, 0, -1, -1, 0, 650, 0);
          canvas.AddTemplate(template, 0, -0.2f, -0.5f, 0, 350, 0);
        }
        return ms.ToArray();
      }
    }
// ===========================================================================
  }
}
TransformationMatrix3.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using iTextSharp.awt.geom;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class TransformationMatrix3 : IWriter {
// ===========================================================================
    /** The resulting PDF. */
    public const String RESULT = "transformation_matrix3.pdf";
    /** A PDF with the iText logo that will be transformed. */
    public readonly string RESOURCE = Path.Combine(
      Utility.ResourcePdf, "logo.pdf"
    );
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        TransformationMatrix3 t = new TransformationMatrix3();
        zip.AddFile(RESOURCE, "");       
        zip.AddEntry(RESULT, t.CreatePdf());
        zip.Save(stream);             
      }
    }     
// ---------------------------------------------------------------------------    
    /**
     * Creates a PDF document.
     */
    public byte[] CreatePdf() {
      // step 1
      Rectangle rect = new Rectangle(-595, -842, 595, 842);
      using (MemoryStream ms = new MemoryStream()) {
        using (Document document = new Document(rect)) {
          // step 2
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          PdfContentByte canvas = writer.DirectContent;
          // draw coordinate system
          canvas.MoveTo(-595, 0);
          canvas.LineTo(595, 0);
          canvas.MoveTo(0, -842);
          canvas.LineTo(0, 842);
          canvas.Stroke();
          // read the PDF with the logo
          PdfReader reader = new PdfReader(RESOURCE);
          PdfTemplate template = writer.GetImportedPage(reader, 1); 
          // add it
          canvas.SaveState();
          canvas.AddTemplate(template, 0, 0);
          AffineTransform af = new AffineTransform();
          af.Translate(-595, 0);
          af.Scale(0.5f, 0.5f);
          canvas.Transform(af);
          canvas.AddTemplate(template, 0, 0);
          canvas.ConcatCTM(AffineTransform.GetTranslateInstance(595, 595));
          canvas.AddTemplate(template, 0, 0);
          canvas.RestoreState();

          canvas.SaveState();
          af = new AffineTransform(1f, 0f, 0.4f, 1f, -750f, -650f);
          canvas.AddTemplate(template, af);
          canvas.RestoreState();
          
          canvas.SaveState();
          af = new AffineTransform(0, -1, -1, 0, 650, 0);
          canvas.AddTemplate(template, af);
          af = new AffineTransform(0, -0.2f, -0.5f, 0, 350, 0);
          canvas.AddTemplate(template, af);
          canvas.RestoreState();         
        }
        return ms.ToArray();
      }
    }
// ===========================================================================
  }
}
TextStateOperators.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class TextStateOperators : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte canvas = writer.DirectContent;
        String text = "AWAY again";
        BaseFont bf = BaseFont.CreateFont();
        canvas.BeginText();
        // line 1
        canvas.SetFontAndSize(bf, 16);
        canvas.MoveText(36, 806);
        canvas.MoveTextWithLeading(0, -24);
        canvas.ShowText(text);
        // line 2
        canvas.SetWordSpacing(20);
        canvas.NewlineShowText(text);
        // line 3
        canvas.SetCharacterSpacing(10);
        canvas.NewlineShowText(text);
        canvas.SetWordSpacing(0);
        canvas.SetCharacterSpacing(0);
        // line 4
        canvas.SetHorizontalScaling(50);
        canvas.NewlineShowText(text);
        canvas.SetHorizontalScaling(100);
        // line 5
        canvas.NewlineShowText(text);
        canvas.SetTextRise(15);
        canvas.SetFontAndSize(bf, 12);
        canvas.SetColorFill(BaseColor.RED);
        canvas.ShowText("2");
        canvas.SetColorFill(GrayColor.GRAYBLACK);
        // line 6
        canvas.SetLeading(56);
        canvas.NewlineShowText("Changing the leading: " + text);
        canvas.SetLeading(24);
        canvas.NewlineText();
        // line 7
        PdfTextArray array = new PdfTextArray("A");
        array.Add(120);
        array.Add("W");
        array.Add(120);
        array.Add("A");
        array.Add(95);
        array.Add("Y again");
        canvas.ShowText(array);
        canvas.EndText();

        canvas.SetColorFill(BaseColor.BLUE);
        canvas.BeginText();
        canvas.SetTextMatrix(360, 770);
        canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
        canvas.SetFontAndSize(bf, 24);
        canvas.ShowText(text);
        canvas.EndText();

        canvas.BeginText();
        canvas.SetTextMatrix(360, 730);
        canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);
        canvas.SetFontAndSize(bf, 24);
        canvas.ShowText(text);
        canvas.EndText();

        canvas.BeginText();
        canvas.SetTextMatrix(360, 690);
        canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
        canvas.SetFontAndSize(bf, 24);
        canvas.ShowText(text);
        canvas.EndText();

        canvas.BeginText();
        canvas.SetTextMatrix(360, 650);
        canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
        canvas.SetFontAndSize(bf, 24);
        canvas.ShowText(text);
        canvas.EndText();

        PdfTemplate template = canvas.CreateTemplate(200, 36);
        template.SetLineWidth(2);
        for (int i = 0; i < 6; i++) {
            template.MoveTo(0, i * 6);
            template.LineTo(200, i * 6);
        }
        template.Stroke();
        
        canvas.SaveState();
        canvas.BeginText();
        canvas.SetTextMatrix(360, 610);
        canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_CLIP);
        canvas.SetFontAndSize(bf, 24);
        canvas.ShowText(text);
        canvas.EndText();
        canvas.AddTemplate(template, 360, 610);
        canvas.RestoreState();

        canvas.SaveState();
        canvas.BeginText();
        canvas.SetTextMatrix(360, 570);
        canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE_CLIP);
        canvas.SetFontAndSize(bf, 24);
        canvas.ShowText(text);
        canvas.EndText();
        canvas.AddTemplate(template, 360, 570);
        canvas.RestoreState();

        canvas.SaveState();
        canvas.BeginText();
        canvas.SetTextMatrix(360, 530);
        canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE_CLIP);
        canvas.SetFontAndSize(bf, 24);
        canvas.ShowText(text);
        canvas.EndText();
        canvas.AddTemplate(template, 360, 530);
        canvas.RestoreState();
        
        canvas.SaveState();
        canvas.BeginText();
        canvas.SetTextMatrix(360, 490);
        canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_CLIP);
        canvas.SetFontAndSize(bf, 24);
        canvas.ShowText(text);
        canvas.EndText();
        canvas.AddTemplate(template, 360, 490);
        canvas.RestoreState();

      }
    }
// ===========================================================================
  }
}
TextMethods.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class TextMethods : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        // draw helper lines
        PdfContentByte cb = writer.DirectContent;
        cb.SetLineWidth(0f);
        cb.MoveTo(150, 600);
        cb.LineTo(150, 800);
        cb.MoveTo(50, 760);
        cb.LineTo(250, 760);
        cb.MoveTo(50, 700);
        cb.LineTo(250, 700);
        cb.MoveTo(50, 640);
        cb.LineTo(250, 640);
        cb.Stroke();
        // draw text
        String text = "AWAY again ";
        BaseFont bf = BaseFont.CreateFont();
        cb.BeginText();
        cb.SetFontAndSize(bf, 12);
        cb.SetTextMatrix(50, 800);
        cb.ShowText(text);
        cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, text + " Center", 150, 760, 0);
        cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, text + " Right", 150, 700, 0);
        cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text + " Left", 150, 640, 0);
        cb.ShowTextAlignedKerned(PdfContentByte.ALIGN_LEFT, text + " Left", 150, 628, 0);
        cb.SetTextMatrix(0, 1, -1, 0, 300, 600);
        cb.ShowText("Position 300,600, rotated 90 degrees.");
        for (int i = 0; i < 360; i += 30) {
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, 400, 700, i);
        }
        cb.EndText();
      }
    }
// ===========================================================================
  }
}
PearExample.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class PearExample : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
PearToPdf.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class PearToPdf : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
DirectorCharts.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class DirectorCharts : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
Graphics2DFonts.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class Graphics2DFonts : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
TextExample1.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class TextExample1 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
Text1ToPdf1.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class Text1ToPdf1 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
Text1ToPdf2.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class Text1ToPdf2 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
TextExample2.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class TextExample2 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
Text2ToPdf1.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class Text2ToPdf1 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
Text2ToPdf2.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class Text2ToPdf2 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
Text2ToPdf3.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class Text2ToPdf3 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
TextExample3.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class TextExample3 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
Text3ToPdf.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class Text3ToPdf : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
TextExample4.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class TextExample4 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
Text4ToPdf.cs
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter14 {
  public class Text4ToPdf : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      throw new NotImplementedException(
        "iTextSharp does not implement Java Graphics2D class"
      );
    }
// ===========================================================================
  }
}
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now