Skip to main content
Skip table of contents

iText Jump-Start Tutorial : Chapter 2

The following examples relate to Chapter 2 of the iText Core Jump-Start Tutorial (Java/.NET)

c02e01_axes

JAVA
JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package tutorial.chapter02;

import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.canvas.PdfCanvasConstants;
import java.io.File;
import java.io.IOException;

/**
 * Simple drawing lines example.
 */
public class C02E01_Axes {

    public static final String DEST = "results/chapter02/axes.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C02E01_Axes().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException {

        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

        PageSize ps = PageSize.A4.rotate();
        PdfPage page = pdf.addNewPage(ps);

        PdfCanvas canvas = new PdfCanvas(page);
        //Replace the origin of the coordinate system to the center of the page
        canvas.concatMatrix(1, 0, 0, 1, ps.getWidth() / 2, ps.getHeight() / 2);

        C02E01_Axes.drawAxes(canvas, ps);

        //Close document
        pdf.close();

    }

    public static void drawAxes(PdfCanvas canvas, PageSize ps) {
        //Draw X axis
        canvas.moveTo(-(ps.getWidth() / 2 - 15), 0)
                .lineTo(ps.getWidth() / 2 - 15, 0)
                .stroke();

        //Draw X axis arrow
        canvas.setLineJoinStyle(PdfCanvasConstants.LineJoinStyle.ROUND)
                .moveTo(ps.getWidth() / 2 - 25, -10)
                .lineTo(ps.getWidth() / 2 - 15, 0)
                .lineTo(ps.getWidth() / 2 - 25, 10).stroke()
                .setLineJoinStyle(PdfCanvasConstants.LineJoinStyle.MITER);

        //Draw Y axis
        canvas.moveTo(0, -(ps.getHeight() / 2 - 15))
                .lineTo(0, ps.getHeight() / 2 - 15)
                .stroke();
        
        //Draw Y axis arrow
        canvas.saveState()
                .setLineJoinStyle(PdfCanvasConstants.LineJoinStyle.ROUND)
                .moveTo(-10, ps.getHeight() / 2 - 25)
                .lineTo(0, ps.getHeight() / 2 - 15)
                .lineTo(10, ps.getHeight() / 2 - 25).stroke()
                .restoreState();

        //Draw X serif
        for (int i = -((int) ps.getWidth() / 2 - 61); i < ((int) ps.getWidth() / 2 - 60); i += 40) {
            canvas.moveTo(i, 5).lineTo(i, -5);
        }
        //Draw Y serif
        for (int j = -((int) ps.getHeight() / 2 - 57); j < ((int) ps.getHeight() / 2 - 56); j += 40) {
            canvas.moveTo(5, j).lineTo(-5, j);
        }
        canvas.stroke();
    }
}

C#

C#
using System;
using System.IO;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;

namespace Tutorial.Chapter02 {
    /// <summary>Simple drawing lines example.</summary>
    public class C02E01_Axes {
        public const String DEST = "../../../results/chapter02/axes.pdf";

        public static void Main(String[] args) {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new C02E01_Axes().CreatePdf(DEST);
        }

        public virtual void CreatePdf(String dest) {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            PageSize ps = PageSize.A4.Rotate();
            PdfPage page = pdf.AddNewPage(ps);
            PdfCanvas canvas = new PdfCanvas(page);
            //Replace the origin of the coordinate system to the center of the page
            canvas.ConcatMatrix(1, 0, 0, 1, ps.GetWidth() / 2, ps.GetHeight() / 2);
            C02E01_Axes.DrawAxes(canvas, ps);
            //Close document
            pdf.Close();
        }

        public static void DrawAxes(PdfCanvas canvas, PageSize ps) {
            //Draw X axis
            canvas.MoveTo(-(ps.GetWidth() / 2 - 15), 0).LineTo(ps.GetWidth() / 2 - 15, 0).Stroke();
            //Draw X axis arrow
            canvas.SetLineJoinStyle(PdfCanvasConstants.LineJoinStyle.ROUND).MoveTo(ps.GetWidth() / 2 - 25, -10).LineTo
                (ps.GetWidth() / 2 - 15, 0).LineTo(ps.GetWidth() / 2 - 25, 10).Stroke().SetLineJoinStyle(PdfCanvasConstants.LineJoinStyle
                .MITER);
            //Draw Y axis
            canvas.MoveTo(0, -(ps.GetHeight() / 2 - 15)).LineTo(0, ps.GetHeight() / 2 - 15).Stroke();
            //Draw Y axis arrow
            canvas.SaveState().SetLineJoinStyle(PdfCanvasConstants.LineJoinStyle.ROUND).MoveTo(-10, ps.GetHeight() / 2
                 - 25).LineTo(0, ps.GetHeight() / 2 - 15).LineTo(10, ps.GetHeight() / 2 - 25).Stroke().RestoreState();
            //Draw X serif
            for (int i = -((int)ps.GetWidth() / 2 - 61); i < ((int)ps.GetWidth() / 2 - 60); i += 40) {
                canvas.MoveTo(i, 5).LineTo(i, -5);
            }
            //Draw Y serif
            for (int j = -((int)ps.GetHeight() / 2 - 57); j < ((int)ps.GetHeight() / 2 - 56); j += 40) {
                canvas.MoveTo(5, j).LineTo(-5, j);
            }
            canvas.Stroke();
        }
    }
}

c02e02_gridlines

JAVA
JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package tutorial.chapter02;

import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.colors.DeviceCmyk;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import java.io.File;
import java.io.IOException;

/**
 * Simple changing graphics state example.
 */
public class C02E02_GridLines {

    public static final String DEST = "results/chapter02/grid_lines.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C02E02_GridLines().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException {

        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

        PageSize ps = PageSize.A4.rotate();
        PdfPage page = pdf.addNewPage(ps);

        PdfCanvas canvas = new PdfCanvas(page);
        //Replace the origin of the coordinate system to the center of the page
        canvas.concatMatrix(1, 0, 0, 1, ps.getWidth() / 2, ps.getHeight() / 2);

        Color grayColor = new DeviceCmyk(0.f, 0.f, 0.f, 0.875f);
        Color greenColor = new DeviceCmyk(1.f, 0.f, 1.f, 0.176f);
        Color blueColor = new DeviceCmyk(1.f, 0.156f, 0.f, 0.118f);
        
        canvas.setLineWidth(0.5f).setStrokeColor(blueColor);

        //Draw horizontal grid lines
        for (int i = -((int) ps.getHeight() / 2 - 57); i < ((int) ps.getHeight() / 2 - 56); i += 40) {
            canvas.moveTo(-(ps.getWidth() / 2 - 15), i)
                    .lineTo(ps.getWidth() / 2 - 15, i);
        }
        //Draw vertical grid lines
        for (int j = -((int) ps.getWidth() / 2 - 61); j < ((int) ps.getWidth() / 2 - 60); j += 40) {
            canvas.moveTo(j, -(ps.getHeight() / 2 - 15))
                    .lineTo(j, ps.getHeight() / 2 - 15);
        }
        canvas.stroke();

        //Draw axes
        canvas.setLineWidth(3).setStrokeColor(grayColor);
        C02E01_Axes.drawAxes(canvas, ps);

        //Draw plot
        canvas.setLineWidth(2).setStrokeColor(greenColor)
                .setLineDash(10, 10, 8)
                .moveTo(-(ps.getWidth() / 2 - 15), -(ps.getHeight() / 2 - 15))
                .lineTo(ps.getWidth() / 2 - 15, ps.getHeight() / 2 - 15).stroke();

        //Close document
        pdf.close();

    }
}
C#
C#
using System;
using System.IO;
using iText.Kernel.Colors;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;

namespace Tutorial.Chapter02 {
    /// <summary>Simple changing graphics state example.</summary>
    public class C02E02_GridLines {
        public const String DEST = "../../../results/chapter02/grid_lines.pdf";

        public static void Main(String[] args) {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new C02E02_GridLines().CreatePdf(DEST);
        }

        public virtual void CreatePdf(String dest) {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            PageSize ps = PageSize.A4.Rotate();
            PdfPage page = pdf.AddNewPage(ps);
            PdfCanvas canvas = new PdfCanvas(page);
            //Replace the origin of the coordinate system to the center of the page
            canvas.ConcatMatrix(1, 0, 0, 1, ps.GetWidth() / 2, ps.GetHeight() / 2);
            Color grayColor = new DeviceCmyk(0f, 0f, 0f, 0.875f);
            Color greenColor = new DeviceCmyk(1f, 0f, 1f, 0.176f);
            Color blueColor = new DeviceCmyk(1f, 0.156f, 0f, 0.118f);
            canvas.SetLineWidth(0.5f).SetStrokeColor(blueColor);
            //Draw horizontal grid lines
            for (int i = -((int)ps.GetHeight() / 2 - 57); i < ((int)ps.GetHeight() / 2 - 56); i += 40) {
                canvas.MoveTo(-(ps.GetWidth() / 2 - 15), i).LineTo(ps.GetWidth() / 2 - 15, i);
            }
            //Draw vertical grid lines
            for (int j = -((int)ps.GetWidth() / 2 - 61); j < ((int)ps.GetWidth() / 2 - 60); j += 40) {
                canvas.MoveTo(j, -(ps.GetHeight() / 2 - 15)).LineTo(j, ps.GetHeight() / 2 - 15);
            }
            canvas.Stroke();
            //Draw axes
            canvas.SetLineWidth(3).SetStrokeColor(grayColor);
            C02E01_Axes.DrawAxes(canvas, ps);
            //Draw plot
            canvas.SetLineWidth(2).SetStrokeColor(greenColor).SetLineDash(10, 10, 8).MoveTo(-(ps.GetWidth() / 2 - 15), 
                -(ps.GetHeight() / 2 - 15)).LineTo(ps.GetWidth() / 2 - 15, ps.GetHeight() / 2 - 15).Stroke();
            //Close document
            pdf.Close();
        }
    }
}

c02e03_starwars

JAVA
JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package tutorial.chapter02;

import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Simple drawing text example.
 */
public class C02E03_StarWars {

    public static final String DEST = "results/chapter02/star_wars.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C02E03_StarWars().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException {

        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

        //Add new page
        PageSize ps = PageSize.A4;
        PdfPage page = pdf.addNewPage(ps);

        PdfCanvas canvas = new PdfCanvas(page);

        List<String> text = new ArrayList();
        text.add("         Episode V         ");
        text.add("  THE EMPIRE STRIKES BACK  ");
        text.add("It is a dark time for the");
        text.add("Rebellion. Although the Death");
        text.add("Star has been destroyed,");
        text.add("Imperial troops have driven the");
        text.add("Rebel forces from their hidden");
        text.add("base and pursued them across");
        text.add("the galaxy.");
        text.add("Evading the dreaded Imperial");
        text.add("Starfleet, a group of freedom");
        text.add("fighters led by Luke Skywalker");
        text.add("has established a new secret");
        text.add("base on the remote ice world");
        text.add("of Hoth...");

        //Replace the origin of the coordinate system to the top left corner
        canvas.concatMatrix(1, 0, 0, 1, 0, ps.getHeight());
        canvas.beginText()
                .setFontAndSize(PdfFontFactory.createFont(StandardFonts.COURIER_BOLD), 14)
                .setLeading(14 * 1.2f)
                .moveText(70, -40);
        for (String s : text) {
            //Add text and move to the next line
            canvas.newlineShowText(s);
        }
        canvas.endText();

        //Close document
        pdf.close();

    }
}
C#
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using iText.IO.Font.Constants;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;

namespace Tutorial.Chapter02 {
    /// <summary>Simple drawing text example.</summary>
    public class C02E03_StarWars {
        public const String DEST = "../../../results/chapter02/star_wars.pdf";

        public static void Main(String[] args) {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new C02E03_StarWars().CreatePdf(DEST);
        }

        public virtual void CreatePdf(String dest) {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            //Add new page
            PageSize ps = PageSize.A4;
            PdfPage page = pdf.AddNewPage(ps);
            PdfCanvas canvas = new PdfCanvas(page);
            IList<String> text = new List<String>();
            text.Add("         Episode V         ");
            text.Add("  THE EMPIRE STRIKES BACK  ");
            text.Add("It is a dark time for the");
            text.Add("Rebellion. Although the Death");
            text.Add("Star has been destroyed,");
            text.Add("Imperial troops have driven the");
            text.Add("Rebel forces from their hidden");
            text.Add("base and pursued them across");
            text.Add("the galaxy.");
            text.Add("Evading the dreaded Imperial");
            text.Add("Starfleet, a group of freedom");
            text.Add("fighters led by Luke Skywalker");
            text.Add("has established a new secret");
            text.Add("base on the remote ice world");
            text.Add("of Hoth...");
            //Replace the origin of the coordinate system to the top left corner
            canvas.ConcatMatrix(1, 0, 0, 1, 0, ps.GetHeight());
            canvas.BeginText().SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER_BOLD), 14).SetLeading(14
                 * 1.2f).MoveText(70, -40);
            foreach (String s in text) {
                //Add text and move to the next line
                canvas.NewlineShowText(s);
            }
            canvas.EndText();
            //Close document
            pdf.Close();
        }
    }
}

c02e04_starwarscrawl

JAVA
JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package tutorial.chapter02;

import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceCmyk;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Simple changing text state example.
 */

public class C02E04_StarWarsCrawl {

    public static final String DEST = "results/chapter02/star_wars_crawl.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C02E04_StarWarsCrawl().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException {

        List<String> text = new ArrayList();
        text.add("            Episode V      ");
        text.add("    THE EMPIRE STRIKES BACK  ");
        text.add("It is a dark time for the");
        text.add("Rebellion. Although the Death");
        text.add("Star has been destroyed,");
        text.add("Imperial troops have driven the");
        text.add("Rebel forces from their hidden");
        text.add("base and pursued them across");
        text.add("the galaxy.");
        text.add("Evading the dreaded Imperial");
        text.add("Starfleet, a group of freedom");
        text.add("fighters led by Luke Skywalker");
        text.add("has established a new secret");
        text.add("base on the remote ice world");
        text.add("of Hoth...");

        int maxStringWidth = 0;
        for (String fragment : text) {
            if (fragment.length() > maxStringWidth) maxStringWidth = fragment.length();
        }

        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

        //Add new page
        PageSize ps = PageSize.A4;
        PdfPage page = pdf.addNewPage(ps);

        PdfCanvas canvas = new PdfCanvas(page);

        //Set black background
        canvas.rectangle(0, 0, ps.getWidth(), ps.getHeight())
                .setColor(ColorConstants.BLACK, true)
                .fill();

        //Replace the origin of the coordinate system to the top left corner
        canvas.concatMatrix(1, 0, 0, 1, 0, ps.getHeight());
        Color yellowColor = new DeviceCmyk(0.f, 0.0537f, 0.769f, 0.051f);
        float lineHeight = 5;
        float yOffset = -40;
        canvas.beginText()
            .setFontAndSize(PdfFontFactory.createFont(StandardFonts.COURIER_BOLD), 1)
            .setColor(yellowColor, true);
        for (int j = 0; j < text.size(); j++) {
            String line = text.get(j);
            float xOffset = ps.getWidth() / 2 - 45 - 8 * j;
            float fontSizeCoeff = 6 + j;
            float lineSpacing = (lineHeight + j) * j / 1.5f;
            int stringWidth = line.length();
            for (int i = 0; i < stringWidth; i++) {
                float angle = (maxStringWidth / 2 - i) / 2f;
                float charXOffset = (4 + (float) j / 2) * i;
                canvas.setTextMatrix(fontSizeCoeff, 0,
                        angle, fontSizeCoeff / 1.5f,
                        xOffset + charXOffset, yOffset - lineSpacing)
                    .showText(String.valueOf(line.charAt(i)));
            }
        }
        canvas.endText();

        //Close document
        pdf.close();

    }
}
C#
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;

namespace Tutorial.Chapter02 {
    /// <summary>Simple changing text state example.</summary>
    public class C02E04_StarWarsCrawl {
        public const String DEST = "../../../results/chapter02/star_wars_crawl.pdf";

        public static void Main(String[] args) {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new C02E04_StarWarsCrawl().CreatePdf(DEST);
        }

        public virtual void CreatePdf(String dest) {
            IList<String> text = new List<String>();
            text.Add("            Episode V      ");
            text.Add("    THE EMPIRE STRIKES BACK  ");
            text.Add("It is a dark time for the");
            text.Add("Rebellion. Although the Death");
            text.Add("Star has been destroyed,");
            text.Add("Imperial troops have driven the");
            text.Add("Rebel forces from their hidden");
            text.Add("base and pursued them across");
            text.Add("the galaxy.");
            text.Add("Evading the dreaded Imperial");
            text.Add("Starfleet, a group of freedom");
            text.Add("fighters led by Luke Skywalker");
            text.Add("has established a new secret");
            text.Add("base on the remote ice world");
            text.Add("of Hoth...");
            int maxStringWidth = 0;
            foreach (String fragment in text) {
                if (fragment.Length > maxStringWidth) {
                    maxStringWidth = fragment.Length;
                }
            }
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            //Add new page
            PageSize ps = PageSize.A4;
            PdfPage page = pdf.AddNewPage(ps);
            PdfCanvas canvas = new PdfCanvas(page);
            //Set black background
            canvas.Rectangle(0, 0, ps.GetWidth(), ps.GetHeight()).SetColor(ColorConstants.BLACK, true).Fill();
            //Replace the origin of the coordinate system to the top left corner
            canvas.ConcatMatrix(1, 0, 0, 1, 0, ps.GetHeight());
            Color yellowColor = new DeviceCmyk(0f, 0.0537f, 0.769f, 0.051f);
            float lineHeight = 5;
            float yOffset = -40;
            canvas.BeginText().SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER_BOLD), 1).SetColor(yellowColor
                , true);
            for (int j = 0; j < text.Count; j++) {
                String line = text[j];
                float xOffset = ps.GetWidth() / 2 - 45 - 8 * j;
                float fontSizeCoeff = 6 + j;
                float lineSpacing = (lineHeight + j) * j / 1.5f;
                int stringWidth = line.Length;
                for (int i = 0; i < stringWidth; i++) {
                    float angle = (maxStringWidth / 2 - i) / 2f;
                    float charXOffset = (4 + (float)j / 2) * i;
                    canvas.SetTextMatrix(fontSizeCoeff, 0, angle, fontSizeCoeff / 1.5f, xOffset + charXOffset, yOffset - lineSpacing
                        ).ShowText(line[i].ToString());
                }
            }
            canvas.EndText();
            //Close document
            pdf.Close();
        }
    }
}

Results

cmp_axes.pdf

cmp_grid_lines.pdf

cmp_star_wars.pdf

cmp_star_wars_crawl.pdf

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.