Chapter 14: The imaging model

These examples were written in the context of Chapter 14 of the book "iText in Action - Second Edition".

Files: 
/*
 * 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);
    }
}
/*
 * 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);
    }
}
/*
 * 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);
    }
}
/*
 * 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);
    }
}
/*
 * 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);
    }
}
/*
 * 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);
    }
}
/*
 * 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);
    }
 
}
/*
 * 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);
    }
 
}
/*
 * 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;
}
/*
 * 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);
    }
}
/*
 * 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);
    }
}
/*
 * 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<String,BaseFontParameters> 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();
    }
}
/*
 * 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;
}
/*
 * 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);
    }
}
/*
 * 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);
    }
}
/*
 * 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;
}
/*
 * 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);
    }
}
/*
 * 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);
    }
}
/*
 * 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);
    }
}
/*
 * 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;
}
/*
 * 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);
    }
}
/*
 * 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);
    }
 
}
/*
 * 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);
    }
}
File nameRaw URLUpdated
GetContentStream.javaGetContentStream.java2015-10-10 3:22 pm
PathConstructionAndPainting.javaPathConstructionAndPainting.java2015-10-10 3:22 pm
GraphicsStateOperators.javaGraphicsStateOperators.java2015-10-10 3:22 pm
TransformationMatrix1.javaTransformationMatrix1.java2015-10-10 3:22 pm
TransformationMatrix2.javaTransformationMatrix2.java2015-10-10 3:22 pm
TransformationMatrix3.javaTransformationMatrix3.java2015-10-10 3:22 pm
TextStateOperators.javaTextStateOperators.java2015-10-10 3:22 pm
TextMethods.javaTextMethods.java2015-10-10 3:22 pm
PearExample.javaPearExample.java2015-10-10 3:22 pm
PearToPdf.javaPearToPdf.java2015-10-10 3:22 pm
DirectorCharts.javaDirectorCharts.java2015-10-10 3:22 pm
Graphics2DFonts.javaGraphics2DFonts.java2015-10-10 3:22 pm
TextExample1.javaTextExample1.java2015-10-10 3:22 pm
Text1ToPdf1.javaText1ToPdf1.java2015-10-10 3:22 pm
Text1ToPdf2.javaText1ToPdf2.java2015-10-10 3:22 pm
TextExample2.javaTextExample2.java2015-10-10 3:22 pm
Text2ToPdf1.javaText2ToPdf1.java2015-10-10 3:22 pm
Text2ToPdf2.javaText2ToPdf2.java2015-10-10 3:22 pm
Text2ToPdf3.javaText2ToPdf3.java2015-10-10 3:22 pm
TextExample3.javaTextExample3.java2015-10-10 3:22 pm
Text3ToPdf.javaText3ToPdf.java2015-10-10 3:22 pm
TextExample4.javaTextExample4.java2015-10-10 3:22 pm
Text4ToPdf.javaText4ToPdf.java2015-10-10 3:22 pm