Skip to main content
Skip table of contents

iText Jump-Start Tutorial : Chapter 5

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

c05e01_addannotationsandcontent

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.chapter05;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfButtonFormField;
import com.itextpdf.forms.fields.PdfFormCreator;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.forms.fields.CheckBoxFormFieldBuilder;
import com.itextpdf.forms.fields.properties.CheckBoxType;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfTextAnnotation;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import java.io.File;
import java.io.IOException;

/**
 * Simple adding annotations example.
 */
public class C05E01_AddAnnotationsAndContent {

    public static final String SRC = "src/main/resources/pdf/job_application.pdf";
    public static final String DEST = "results/chapter05/edited_job_application.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C05E01_AddAnnotationsAndContent().manipulatePdf(SRC, DEST);
    }

    public void manipulatePdf(String src, String dest) throws IOException {

        //Initialize PDF document
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));

        //Add text annotation
        PdfAnnotation ann = new PdfTextAnnotation(new Rectangle(400, 795, 0, 0))
                .setOpen(true)
                .setTitle(new PdfString("iText"))
                .setContents("Please, fill out the form.");
        pdfDoc.getFirstPage().addAnnotation(ann);

        PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
        canvas.beginText().setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 12)
                .moveText(265, 597)
                .showText("I agree to the terms and conditions.")
                .endText();

        //Add form field
        PdfAcroForm form = PdfFormCreator.getAcroForm(pdfDoc, true);
        PdfButtonFormField checkField = new CheckBoxFormFieldBuilder(pdfDoc, "agreement")
                .setWidgetRectangle(new Rectangle(245, 594, 15, 15))
                .setCheckType(CheckBoxType.CHECK).createCheckBox();
        checkField.setValue("Off", true);
        checkField.setRequired(true);
        form.addField(checkField);

        //Update reset button
        form.getField("reset").getFirstFormAnnotation().setAction(PdfAction.createResetForm(new String[]{"name",
                "language", "experience1", "experience2", "experience3", "shift", "info", "agreement"}, 0));

        pdfDoc.close();

    }
}
C#
C#
using System;
using System.IO;
using iText.Forms;
using iText.Forms.Fields;
using iText.Forms.Fields.Properties;
using iText.IO.Font.Constants;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using iText.Kernel.Pdf.Annot;
using iText.Kernel.Pdf.Canvas;

namespace Tutorial.Chapter05 {
    /// <summary>Simple adding annotations example.</summary>
    public class C05E01_AddAnnotationsAndContent {
        public const String SRC = "../../../resources/pdf/job_application.pdf";

        public const String DEST = "../../../results/chapter05/edited_job_application.pdf";

        public static void Main(String[] args) {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new C05E01_AddAnnotationsAndContent().ManipulatePdf(SRC, DEST);
        }

        public virtual void ManipulatePdf(String src, String dest) {
            //Initialize PDF document
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
            //Add text annotation
            PdfAnnotation ann = new PdfTextAnnotation(new Rectangle(400, 795, 0, 0))
                .SetOpen(true)
                .SetTitle(new PdfString("iText"))
                .SetContents("Please, fill out the form.");
            pdfDoc.GetFirstPage().AddAnnotation(ann);
            PdfCanvas canvas = new PdfCanvas(pdfDoc.GetFirstPage());
            canvas.BeginText().SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 12).MoveText(265, 597
                ).ShowText("I agree to the terms and conditions.").EndText();
            //Add form field
            PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true);
            PdfButtonFormField checkField = new CheckBoxFormFieldBuilder(pdfDoc, "agreement")
                    .SetWidgetRectangle(new Rectangle(245, 594, 15, 15))
                    .SetCheckType(CheckBoxType.CHECK).CreateCheckBox();
            checkField.SetValue("Off");
            checkField.SetRequired(true);
            form.AddField(checkField);
            //Update reset button
            form.GetField("reset").GetFirstFormAnnotation().SetAction(PdfAction.CreateResetForm(new String[] { "name", "language", "experience1"
                , "experience2", "experience3", "shift", "info", "agreement" }, 0));
            pdfDoc.Close();
        }
    }
}

c05e02_fillandmodifyform

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.chapter05;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormCreator;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Simple filling out form example.
 */
public class C05E02_FillAndModifyForm {

    public static final String SRC = "src/main/resources/pdf/job_application.pdf";
    public static final String DEST = "results/chapter05/filled_out_job_application.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C05E02_FillAndModifyForm().manipulatePdf(SRC, DEST);
    }

    public void manipulatePdf(String src, String dest) throws IOException {

        //Initialize PDF document
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));


        PdfAcroForm form = PdfFormCreator.getAcroForm(pdfDoc, true);
        Map<String, PdfFormField> fields = form.getAllFormFields();

        fields.get("name").setValue("James Bond").getFirstFormAnnotation().setBackgroundColor(ColorConstants.ORANGE);
        fields.get("language").setValue("English");

        fields.get("experience1").setValue("Yes");
        fields.get("experience2").setValue("Yes");
        fields.get("experience3").setValue("Yes");

        List<PdfString> options = new ArrayList<PdfString>();
        options.add(new PdfString("Any"));
        options.add(new PdfString("8.30 am - 12.30 pm"));
        options.add(new PdfString("12.30 pm - 4.30 pm"));
        options.add(new PdfString("4.30 pm - 8.30 pm"));
        options.add(new PdfString("8.30 pm - 12.30 am"));
        options.add(new PdfString("12.30 am - 4.30 am"));
        options.add(new PdfString("4.30 am - 8.30 am"));
        PdfArray arr = new PdfArray(options);
        fields.get("shift").setOptions(arr);
        fields.get("shift").setValue("Any");

        PdfFont courier = PdfFontFactory.createFont(StandardFonts.COURIER);
        fields.get("info").setValue("I was 38 years old when I became an MI6 agent.", courier, 7f);

        pdfDoc.close();

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

namespace Tutorial.Chapter05 {
    /// <summary>Simple filling out form example.</summary>
    public class C05E02_FillAndModifyForm {
        public const String SRC = "../../../resources/pdf/job_application.pdf";

        public const String DEST = "../../../results/chapter05/filled_out_job_application.pdf";

        public static void Main(String[] args) {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new C05E02_FillAndModifyForm().ManipulatePdf(SRC, DEST);
        }

        public virtual void ManipulatePdf(String src, String dest) {
            //Initialize PDF document
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
            PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true);
            IDictionary<String, PdfFormField> fields = form.GetAllFormFields();
            fields["name"].SetValue("James Bond").GetFirstFormAnnotation().SetBackgroundColor(ColorConstants.ORANGE);
            fields["language"].SetValue("English");
            fields["experience1"].SetValue("Yes");
            fields["experience2"].SetValue("Yes");
            fields["experience3"].SetValue("Yes");
            IList<PdfObject> options = new List<PdfObject>();
            options.Add(new PdfString("Any"));
            options.Add(new PdfString("8.30 am - 12.30 pm"));
            options.Add(new PdfString("12.30 pm - 4.30 pm"));
            options.Add(new PdfString("4.30 pm - 8.30 pm"));
            options.Add(new PdfString("8.30 pm - 12.30 am"));
            options.Add(new PdfString("12.30 am - 4.30 am"));
            options.Add(new PdfString("4.30 am - 8.30 am"));
            PdfArray arr = new PdfArray(options);
            fields["shift"].SetOptions(arr);
            fields["shift"].SetValue("Any");
            PdfFont courier = PdfFontFactory.CreateFont(StandardFonts.COURIER);
            fields["info"].SetValue("I was 38 years old when I became an MI6 agent.", courier, 7f);
            pdfDoc.Close();
        }
    }
}

c05e03_addcontent

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.chapter05;

import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.extgstate.PdfExtGState;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.VerticalAlignment;
import java.io.File;
import java.io.IOException;

/**
 * Simple adding content example.
 */
public class C05E03_AddContent {

    public static final String SRC = "src/main/resources/pdf/ufo.pdf";

    public static final String DEST = "results/chapter05/add_content.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C05E03_AddContent().manipulatePdf(SRC, DEST);
    }

    public void manipulatePdf(String src, String dest) throws IOException {

        //Initialize PDF document
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));

        Document document = new Document(pdfDoc);
        Rectangle pageSize;
        PdfCanvas canvas;
        int n = pdfDoc.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
            PdfPage page = pdfDoc.getPage(i);
            pageSize = page.getPageSize();
            canvas = new PdfCanvas(page);
            //Draw header text
            canvas.beginText().setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 7)
                    .moveText(pageSize.getWidth() / 2 - 24, pageSize.getHeight() - 10)
                    .showText("I want to believe")
                    .endText();
            //Draw footer line
            canvas.setStrokeColor(ColorConstants.BLACK)
                    .setLineWidth(.2f)
                    .moveTo(pageSize.getWidth() / 2 - 30, 20)
                    .lineTo(pageSize.getWidth() / 2 + 30, 20).stroke();
            //Draw page number
            canvas.beginText().setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 7)
                    .moveText(pageSize.getWidth() / 2 - 7, 10)
                    .showText(String.valueOf(i))
                    .showText(" of ")
                    .showText(String.valueOf(n))
                    .endText();
            //Draw watermark
            Paragraph p = new Paragraph("CONFIDENTIAL").setFontSize(60);
            canvas.saveState();
            PdfExtGState gs1 = new PdfExtGState().setFillOpacity(0.2f);
            canvas.setExtGState(gs1);
            document.showTextAligned(p,
                    pageSize.getWidth() / 2, pageSize.getHeight() / 2,
                    pdfDoc.getPageNumber(page),
                    TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
            canvas.restoreState();
        }

        pdfDoc.close();

    }
}
C#
C#
using System;
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;
using iText.Kernel.Pdf.Extgstate;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;

namespace Tutorial.Chapter05 {
    /// <summary>Simple adding content example.</summary>
    public class C05E03_AddContent {
        public const String SRC = "../../../resources/pdf/ufo.pdf";

        public const String DEST = "../../../results/chapter05/add_content.pdf";

        public static void Main(String[] args) {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new C05E03_AddContent().ManipulatePdf(SRC, DEST);
        }

        public virtual void ManipulatePdf(String src, String dest) {
            //Initialize PDF document
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
            Document document = new Document(pdfDoc);
            Rectangle pageSize;
            PdfCanvas canvas;
            int n = pdfDoc.GetNumberOfPages();
            for (int i = 1; i <= n; i++) {
                PdfPage page = pdfDoc.GetPage(i);
                pageSize = page.GetPageSize();
                canvas = new PdfCanvas(page);
                //Draw header text
                canvas.BeginText().SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 7).MoveText(pageSize
                    .GetWidth() / 2 - 24, pageSize.GetHeight() - 10).ShowText("I want to believe").EndText();
                //Draw footer line
                canvas.SetStrokeColor(ColorConstants.BLACK).SetLineWidth(.2f).MoveTo(pageSize.GetWidth() / 2 - 30, 20).LineTo(pageSize
                    .GetWidth() / 2 + 30, 20).Stroke();
                //Draw page number
                canvas.BeginText().SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 7).MoveText(pageSize
                    .GetWidth() / 2 - 7, 10).ShowText(i.ToString()).ShowText(" of ").ShowText(n.ToString()).EndText();
                //Draw watermark
                Paragraph p = new Paragraph("CONFIDENTIAL").SetFontSize(60);
                canvas.SaveState();
                PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(0.2f);
                canvas.SetExtGState(gs1);
                document.ShowTextAligned(p, pageSize.GetWidth() / 2, pageSize.GetHeight() / 2, pdfDoc.GetPageNumber(page), 
                    TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
                canvas.RestoreState();
            }
            pdfDoc.Close();
        }
    }
}

c05e04_changepage

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.chapter05;

import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import java.io.File;
import java.io.IOException;

/**
 * Simple changing page properties example.
 */
public class C05E04_ChangePage {

    public static final String SRC = "src/main/resources/pdf/ufo.pdf";
    public static final String DEST = "results/chapter05/change_page.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C05E04_ChangePage().manipulatePdf(SRC, DEST);
    }

    public void manipulatePdf(String src, String dest) throws IOException {

        //Initialize PDF document
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));


        float margin = 72;
        for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
            PdfPage page = pdfDoc.getPage(i);
            // change page size
            Rectangle mediaBox = page.getMediaBox();
            Rectangle newMediaBox = new Rectangle(mediaBox.getLeft() - margin, mediaBox.getBottom() - margin,
                    mediaBox.getWidth() + margin * 2, mediaBox.getHeight() + margin * 2);
            page.setMediaBox(newMediaBox);
            // add border
            PdfCanvas over = new PdfCanvas(page);
            over.setStrokeColor(ColorConstants.GRAY);
            over.rectangle(mediaBox.getLeft(), mediaBox.getBottom(), mediaBox.getWidth(), mediaBox.getHeight());
            over.stroke();
            // change rotation of the even pages
            if (i % 2 == 0) {
                page.setRotation(180);
            }
        }

        pdfDoc.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.Chapter05 {
    /// <summary>Simple changing page properties example.</summary>
    public class C05E04_ChangePage {
        public const String SRC = "../../../resources/pdf/ufo.pdf";

        public const String DEST = "../../../results/chapter05/change_page.pdf";

        public static void Main(String[] args) {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new C05E04_ChangePage().ManipulatePdf(SRC, DEST);
        }

        public virtual void ManipulatePdf(String src, String dest) {
            //Initialize PDF document
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
            float margin = 72;
            for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++) {
                PdfPage page = pdfDoc.GetPage(i);
                // change page size
                Rectangle mediaBox = page.GetMediaBox();
                Rectangle newMediaBox = new Rectangle(mediaBox.GetLeft() - margin, mediaBox.GetBottom() - margin, mediaBox
                    .GetWidth() + margin * 2, mediaBox.GetHeight() + margin * 2);
                page.SetMediaBox(newMediaBox);
                // add border
                PdfCanvas over = new PdfCanvas(page);
                over.SetStrokeColor(ColorConstants.GRAY);
                over.Rectangle(mediaBox.GetLeft(), mediaBox.GetBottom(), mediaBox.GetWidth(), mediaBox.GetHeight());
                over.Stroke();
                // change rotation of the even pages
                if (i % 2 == 0) {
                    page.SetRotation(180);
                }
            }
            pdfDoc.Close();
        }
    }
}

Resources

job_application.pdf
ufo.pdf

Results

cmp_edited_job_application.pdf

cmp_filled_out_job_application.pdf

cmp_add_content.pdf

cmp_change_page.pdf

JavaScript errors detected

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

If this problem persists, please contact our support.