Skip to main content
Skip table of contents

iText 7 jump-start tutorial : Chapter 3


c03e01_newyorktimes

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

import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.ColumnDocumentRenderer;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Simple column renderer example.
 */
public class C03E01_NewYorkTimes {

    public static final String DEST = "results/chapter03/new_york_times.pdf";

    public static final String APPLE_IMG = "src/main/resources/img/ny_times_apple.jpg";
    public static final String APPLE_TXT = "src/main/resources/data/ny_times_apple.txt";
    public static final String FACEBOOK_IMG = "src/main/resources/img/ny_times_fb.jpg";
    public static final String FACEBOOK_TXT = "src/main/resources/data/ny_times_fb.txt";
    public static final String INST_IMG = "src/main/resources/img/ny_times_inst.jpg";
    public static final String INST_TXT = "src/main/resources/data/ny_times_inst.txt";

    static PdfFont timesNewRoman = null;
    static PdfFont timesNewRomanBold = null;

    public static void main(String[] args) throws Exception {
        timesNewRoman = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
        timesNewRomanBold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C03E01_NewYorkTimes().createPdf(DEST);
    }

    protected void createPdf(String dest) throws Exception {

        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
        PageSize ps = PageSize.A5;

        // Initialize document
        Document document = new Document(pdf, ps);

        //Set column parameters
        float offSet = 36;
        float columnWidth = (ps.getWidth() - offSet * 2 + 10) / 3;
        float columnHeight = ps.getHeight() - offSet * 2;

        //Define column areas
        Rectangle[] columns = {new Rectangle(offSet - 5, offSet, columnWidth, columnHeight),
                new Rectangle(offSet + columnWidth, offSet, columnWidth, columnHeight),
                new Rectangle(offSet + columnWidth * 2 + 5, offSet, columnWidth, columnHeight)};
        document.setRenderer(new ColumnDocumentRenderer(document, columns));

        Image apple = new Image(ImageDataFactory.create(APPLE_IMG)).setWidth(columnWidth);
        String articleApple = new String(Files.readAllBytes(Paths.get(APPLE_TXT)), StandardCharsets.UTF_8);
        C03E01_NewYorkTimes.addArticle(document, "Apple Encryption Engineers, if Ordered to Unlock iPhone, Might Resist", "By JOHN MARKOFF MARCH 18, 2016", apple, articleApple);
        Image facebook = new Image(ImageDataFactory.create(FACEBOOK_IMG)).setWidth(columnWidth);
        String articleFB = new String(Files.readAllBytes(Paths.get(FACEBOOK_TXT)), StandardCharsets.UTF_8);
        C03E01_NewYorkTimes.addArticle(document, "With \"Smog Jog\" Through Beijing, Zuckerberg Stirs Debate on Air Pollution", "By PAUL MOZUR MARCH 18, 2016", facebook, articleFB);
        Image inst = new Image(ImageDataFactory.create(INST_IMG)).setWidth(columnWidth);
        String articleInstagram = new String(Files.readAllBytes(Paths.get(INST_TXT)), StandardCharsets.UTF_8);
        C03E01_NewYorkTimes.addArticle(document, "Instagram May Change Your Feed, Personalizing It With an Algorithm","By MIKE ISAAC MARCH 15, 2016", inst, articleInstagram);

        document.close();

    }

    public static void addArticle(Document doc, String title, String author, Image img, String text) throws IOException {
        Paragraph p1 = new Paragraph(title)
                .setFont(timesNewRomanBold)
                .setFontSize(14);
        doc.add(p1);
        doc.add(img);
        Paragraph p2 = new Paragraph()
                .setFont(timesNewRoman)
                .setFontSize(7)
                .setFontColor(ColorConstants.GRAY)
                .add(author);
        doc.add(p2);
        Paragraph p3 = new Paragraph()
                .setFont(timesNewRoman)
                .setFontSize(10)
                .add(text);
        doc.add(p3);
    }
}

C#

C#
using System;
using System.IO;
using System.Text;
using iText.IO.Font.Constants;
using iText.IO.Image;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;

namespace Tutorial.Chapter03 {
    /// <summary>Simple column renderer example.</summary>
    public class C03E01_NewYorkTimes {
        public const String DEST = "../../../results/chapter03/new_york_times.pdf";

        public const String APPLE_IMG = "../../../resources/img/ny_times_apple.jpg";

        public const String APPLE_TXT = "../../../resources/data/ny_times_apple.txt";

        public const String FACEBOOK_IMG = "../../../resources/img/ny_times_fb.jpg";

        public const String FACEBOOK_TXT = "../../../resources/data/ny_times_fb.txt";

        public const String INST_IMG = "../../../resources/img/ny_times_inst.jpg";

        public const String INST_TXT = "../../../resources/data/ny_times_inst.txt";

        internal static PdfFont timesNewRoman = null;

        internal static PdfFont timesNewRomanBold = null;

        public static void Main(String[] args) {
            timesNewRoman = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
            timesNewRomanBold = PdfFontFactory.CreateFont(StandardFonts.TIMES_BOLD);
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new C03E01_NewYorkTimes().CreatePdf(DEST);
        }

        protected internal virtual void CreatePdf(String dest) {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            PageSize ps = PageSize.A5;
            // Initialize document
            Document document = new Document(pdf, ps);
            //Set column parameters
            float offSet = 36;
            float columnWidth = (ps.GetWidth() - offSet * 2 + 10) / 3;
            float columnHeight = ps.GetHeight() - offSet * 2;
            //Define column areas
            Rectangle[] columns = new Rectangle[] {
                new Rectangle(offSet - 5, offSet, columnWidth, columnHeight),
                new Rectangle(offSet + columnWidth, offSet, columnWidth, columnHeight),
                new Rectangle(offSet + columnWidth * 2 + 5, offSet, columnWidth, columnHeight)
            };
            //
            document.SetRenderer(new ColumnDocumentRenderer(document, columns));
            Image apple = new Image(ImageDataFactory.Create(APPLE_IMG)).SetWidth(columnWidth);
            String articleApple = File.ReadAllText(System.IO.Path.Combine(APPLE_TXT), Encoding.UTF8);
            C03E01_NewYorkTimes.AddArticle(document, "Apple Encryption Engineers, if Ordered to Unlock iPhone, Might Resist"
                , "By JOHN MARKOFF MARCH 18, 2016", apple, articleApple);

            Image facebook = new Image(ImageDataFactory.Create(FACEBOOK_IMG)
                ).SetWidth(columnWidth);
            String articleFB = File.ReadAllText(System.IO.Path.Combine(FACEBOOK_TXT), Encoding.UTF8);
            C03E01_NewYorkTimes.AddArticle(document, "With \"Smog Jog\" Through Beijing, Zuckerberg Stirs Debate on Air Pollution"
                , "By PAUL MOZUR MARCH 18, 2016", facebook, articleFB);

            Image inst = new Image(ImageDataFactory.Create(INST_IMG)).SetWidth(columnWidth);
            String articleInstagram = File.ReadAllText(System.IO.Path.Combine(INST_TXT), Encoding.UTF8);
            C03E01_NewYorkTimes.AddArticle(document, "Instagram May Change Your Feed, Personalizing It With an Algorithm"
                , "By MIKE ISAAC MARCH 15, 2016", inst, articleInstagram);

            document.Close();
        }

        public static void AddArticle(Document doc, String title, String author, iText.Layout.Element.Image img, String text) {
            Paragraph p1 = new Paragraph(title).SetFont(timesNewRomanBold).SetFontSize(14);
            doc.Add(p1);
            doc.Add(img);
            Paragraph p2 = new Paragraph().SetFont(timesNewRoman).SetFontSize(7).SetFontColor(ColorConstants.GRAY).Add(author);
            doc.Add(p2);
            Paragraph p3 = new Paragraph().SetFont(timesNewRoman).SetFontSize(10).Add(text);
            doc.Add(p3);
        }
    }
}


c03e02_premierleague

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

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.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DrawContext;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.StringTokenizer;

/**
 * Simple table renderer example.
 */
public class C03E02_PremierLeague {

    public static final String DATA = "src/main/resources/data/premier_league.csv";
    public static final String DEST = "results/chapter03/premier_league.pdf";

    Color greenColor = new DeviceCmyk(0.78f, 0, 0.81f, 0.21f);
    Color yellowColor = new DeviceCmyk(0, 0, 0.76f, 0.01f);
    Color redColor = new DeviceCmyk(0, 0.76f, 0.86f, 0.01f);
    Color blueColor = new DeviceCmyk(0.28f, 0.11f, 0, 0);

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

    public void createPdf(String dest) throws IOException {

        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
        PageSize ps = new PageSize(842, 680);

        // Initialize document
        Document document = new Document(pdf, ps);

        PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA);
        PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
        Table table = new Table(UnitValue.createPercentArray(new float[]{1.5f, 7, 2, 2, 2, 2, 3, 4, 4, 2}));
        table
                .setTextAlignment(TextAlignment.CENTER)
                .setHorizontalAlignment(HorizontalAlignment.CENTER);

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(DATA), StandardCharsets.UTF_8));
        String line = br.readLine();
        process(table, line, bold, true);
        while ((line = br.readLine()) != null) {
            process(table, line, font, false);
        }
        br.close();

        document.add(table);

        //Close document
        document.close();

    }

    public void process(Table table, String line, PdfFont font, boolean isHeader) {
        StringTokenizer tokenizer = new StringTokenizer(line, ";");
        int columnNumber = 0;
        while (tokenizer.hasMoreTokens()) {
            if (isHeader) {
                Cell cell = new Cell().add(new Paragraph(tokenizer.nextToken()));
                cell.setNextRenderer(new RoundedCornersCellRenderer(cell));
                cell.setPadding(5).setBorder(null);
                table.addHeaderCell(cell);
            } else {
                columnNumber++;
                Cell cell = new Cell().add(new Paragraph(tokenizer.nextToken()));
                cell.setFont(font).setBorder(new SolidBorder(ColorConstants.BLACK, 0.5f));
                switch (columnNumber) {
                    case 4:
                        cell.setBackgroundColor(greenColor);
                        break;
                    case 5:
                        cell.setBackgroundColor(yellowColor);
                        break;
                    case 6:
                        cell.setBackgroundColor(redColor);
                        break;
                    default:
                        cell.setBackgroundColor(blueColor);
                        break;
                }
                table.addCell(cell);
            }
        }
    }


    private class RoundedCornersCellRenderer extends CellRenderer {
        public RoundedCornersCellRenderer(Cell modelElement) {
            super(modelElement);
        }

        @Override
        public void drawBorder(DrawContext drawContext) {
            Rectangle rectangle = getOccupiedAreaBBox();
            float llx = rectangle.getX() + 1;
            float lly = rectangle.getY() + 1;
            float urx = rectangle.getX() + getOccupiedAreaBBox().getWidth() - 1;
            float ury = rectangle.getY() + getOccupiedAreaBBox().getHeight() - 1;
            PdfCanvas canvas = drawContext.getCanvas();
            float r = 4;
            float b = 0.4477f;
            canvas.moveTo(llx, lly).lineTo(urx, lly).lineTo(urx, ury - r)
                    .curveTo(urx, ury - r * b, urx - r * b, ury, urx - r, ury)
                    .lineTo(llx + r, ury)
                    .curveTo(llx + r * b, ury, llx, ury - r * b, llx, ury - r)
                    .lineTo(llx, lly).stroke();
            super.drawBorder(drawContext);
        }
    }

}

C#

C#
using System;
using System.IO;
using iText.Commons.Utils;
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.Layout;
using iText.Layout.Borders;
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.Layout.Renderer;

namespace Tutorial.Chapter03 {
    /// <summary>Simple table renderer example.</summary>
    public class C03E02_PremierLeague {
        public const String DATA = "../../../resources/data/premier_league.csv";

        public const String DEST = "../../../results/chapter03/premier_league.pdf";

        internal Color greenColor = new DeviceCmyk(0.78f, 0, 0.81f, 0.21f);

        internal Color yellowColor = new DeviceCmyk(0, 0, 0.76f, 0.01f);

        internal Color redColor = new DeviceCmyk(0, 0.76f, 0.86f, 0.01f);

        internal Color blueColor = new DeviceCmyk(0.28f, 0.11f, 0, 0);

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

        public virtual void CreatePdf(String dest) {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            PageSize ps = new PageSize(842, 680);
            // Initialize document
            Document document = new Document(pdf, ps);
            PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
            PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
            Table table = new Table(UnitValue.CreatePercentArray(new float[] { 1.5f, 7, 2, 2, 2, 2, 3, 4, 4, 2 }));
            table.SetTextAlignment(TextAlignment.CENTER).SetHorizontalAlignment(HorizontalAlignment
                .CENTER);
            using (StreamReader sr = File.OpenText(DATA))
            {
                String line = sr.ReadLine();
                Process(table, line, bold, true);
                while ((line = sr.ReadLine()) != null)
                {
                    Process(table, line, font, false);
                }
            }

            document.Add(table);
            //Close document
            document.Close();
        }

        public virtual void Process(Table table, String line, PdfFont font, bool isHeader) {
            StringTokenizer tokenizer = new StringTokenizer(line, ";");
            int columnNumber = 0;
            while (tokenizer.HasMoreTokens()) {
                if (isHeader) {
                    Cell cell = new Cell().Add(new Paragraph(tokenizer.NextToken()));
                    cell.SetNextRenderer(new C03E02_PremierLeague.RoundedCornersCellRenderer(this, cell));
                    cell.SetPadding(5).SetBorder(null);
                    table.AddHeaderCell(cell);
                }
                else {
                    columnNumber++;
                    Cell cell = new Cell().Add(new Paragraph(tokenizer.NextToken()));
                    cell.SetFont(font).SetBorder(new SolidBorder(ColorConstants.BLACK, 0.5f));
                    switch (columnNumber) {
                        case 4: {
                            cell.SetBackgroundColor(greenColor);
                            break;
                        }

                        case 5: {
                            cell.SetBackgroundColor(yellowColor);
                            break;
                        }

                        case 6: {
                            cell.SetBackgroundColor(redColor);
                            break;
                        }

                        default: {
                            cell.SetBackgroundColor(blueColor);
                            break;
                        }
                    }
                    table.AddCell(cell);
                }
            }
        }

        private class RoundedCornersCellRenderer : CellRenderer {
            public RoundedCornersCellRenderer(C03E02_PremierLeague _enclosing, Cell modelElement)
                : base(modelElement) {
                this._enclosing = _enclosing;
            }

            public override void DrawBorder(DrawContext drawContext) {
                Rectangle rectangle = this.GetOccupiedAreaBBox();
                float llx = rectangle.GetX() + 1;
                float lly = rectangle.GetY() + 1;
                float urx = rectangle.GetX() + this.GetOccupiedAreaBBox().GetWidth() - 1;
                float ury = rectangle.GetY() + this.GetOccupiedAreaBBox().GetHeight() - 1;
                PdfCanvas canvas = drawContext.GetCanvas();
                float r = 4;
                float b = 0.4477f;
                canvas.MoveTo(llx, lly).LineTo(urx, lly).LineTo(urx, ury - r).CurveTo(urx, ury - r * b, urx - r * b, ury, 
                    urx - r, ury).LineTo(llx + r, ury).CurveTo(llx + r * b, ury, llx, ury - r * b, llx, ury - r).LineTo(llx
                    , lly).Stroke();
                base.DrawBorder(drawContext);
            }

            private readonly C03E02_PremierLeague _enclosing;
        }
    }
}


c03e03_ufo

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

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.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
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.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.Property;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.properties.VerticalAlignment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;

/**
 * Simple event handler example.
 */
public class C03E03_UFO {

    public static final String DATA = "src/main/resources/data/ufo.csv";
    public static final String DEST = "results/chapter03/ufo.pdf";

    static PdfFont helvetica = null;
    static PdfFont helveticaBold = null;

    public static void main(String[] args) throws Exception {
        helvetica = PdfFontFactory.createFont(StandardFonts.HELVETICA);
        helveticaBold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C03E03_UFO().createPdf(DEST);
    }

    protected void createPdf(String dest) throws Exception {

        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
        pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new MyEventHandler());

        // Initialize document
        Document document = new Document(pdf);

        Paragraph p = new Paragraph("List of reported UFO sightings in 20th century")
                .setTextAlignment(TextAlignment.CENTER).setFont(helveticaBold).setFontSize(14);
        document.add(p);

        Table table = new Table(UnitValue.createPercentArray(new float[]{3, 5, 7, 4}));

        BufferedReader br = new BufferedReader(new FileReader(DATA));
        String line = br.readLine();
        process(table, line, helveticaBold, true);
        while ((line = br.readLine()) != null) {
            process(table, line, helvetica, false);
        }
        br.close();

        document.add(table);

        document.close();
    }

    public void process(Table table, String line, PdfFont font, boolean isHeader) {
        StringTokenizer tokenizer = new StringTokenizer(line, ";");
        while (tokenizer.hasMoreTokens()) {
            if (isHeader) {
                table.addHeaderCell(new Cell().add(new Paragraph(tokenizer.nextToken()).setFont(font)).setFontSize(9).setBorder(new SolidBorder(ColorConstants.BLACK, 0.5f)));
            } else {
                table.addCell(new Cell().add(new Paragraph(tokenizer.nextToken()).setFont(font)).setFontSize(9).setBorder(new SolidBorder(ColorConstants.BLACK, 0.5f)));
            }
        }
    }


    protected class MyEventHandler implements IEventHandler {

        public void handleEvent(Event event) {
            PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
            PdfDocument pdfDoc = docEvent.getDocument();
            PdfPage page = docEvent.getPage();
            int pageNumber = pdfDoc.getPageNumber(page);
            Rectangle pageSize = page.getPageSize();
            PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);

            //Set background
            Color limeColor = new DeviceCmyk(0.208f, 0, 0.584f, 0);
            Color blueColor = new DeviceCmyk(0.445f, 0.0546f, 0, 0.0667f);
            pdfCanvas.saveState()
                    .setFillColor(pageNumber % 2 == 1 ? limeColor : blueColor)
                    .rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight())
                    .fill().restoreState();

            //Add header and footer
            pdfCanvas.beginText()
                    .setFontAndSize(helvetica, 9)
                    .moveText(pageSize.getWidth() / 2 - 60, pageSize.getTop() - 20)
                    .showText("THE TRUTH IS OUT THERE")
                    .moveText(60, -pageSize.getTop() + 30)
                    .showText(String.valueOf(pageNumber))
                    .endText();

            //Add watermark
            Canvas canvas = new Canvas(pdfCanvas, page.getPageSize());
            canvas.setFontColor(ColorConstants.WHITE);
            canvas.setProperty(Property.FONT_SIZE, UnitValue.createPointValue(60));
            canvas.setProperty(Property.FONT, helveticaBold);
            canvas.showTextAligned(new Paragraph("CONFIDENTIAL"), 298, 421, pdfDoc.getPageNumber(page),
                            TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);

            pdfCanvas.release();
        }
    }
}

C#

C#
using System;
using System.IO;
using iText.Commons.Utils;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Events;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout;
using iText.Layout.Borders;
using iText.Layout.Element;
using iText.Layout.Properties;

namespace Tutorial.Chapter03 {
    /// <summary>Simple event handler example.</summary>
    public class C03E03_UFO {
        public const String DATA = "../../../resources/data/ufo.csv";

        public const String DEST = "../../../results/chapter03/ufo.pdf";

        internal static PdfFont helvetica = null;

        internal static PdfFont helveticaBold = null;

        public static void Main(String[] args) {
            helvetica = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
            helveticaBold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new C03E03_UFO().CreatePdf(DEST);
        }

        protected internal virtual void CreatePdf(String dest) {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new C03E03_UFO.MyEventHandler(this));
            // Initialize document
            Document document = new Document(pdf);
            Paragraph p = new Paragraph("List of reported UFO sightings in 20th century").SetTextAlignment(TextAlignment
                .CENTER).SetFont(helveticaBold).SetFontSize(14);
            document.Add(p);
            Table table = new Table(UnitValue.CreatePercentArray(new float[] { 3, 5, 7, 4 }));
            using (StreamReader sr = File.OpenText(DATA))
            {
                String line = sr.ReadLine();
                Process(table, line, helveticaBold, true);
                while ((line = sr.ReadLine()) != null)
                {
                    Process(table, line, helvetica, false);
                }
            }

            document.Add(table);
            document.Close();
        }

        public virtual void Process(Table table, String line, PdfFont font, bool isHeader) {
            StringTokenizer tokenizer = new StringTokenizer(line, ";");
            while (tokenizer.HasMoreTokens()) {
                if (isHeader) {
                    table.AddHeaderCell(new Cell().Add(new Paragraph(tokenizer.NextToken()).SetFont(font)).SetFontSize(9).SetBorder
                        (new SolidBorder(ColorConstants.BLACK, 0.5f)));
                }
                else {
                    table.AddCell(new Cell().Add(new Paragraph(tokenizer.NextToken()).SetFont(font)).SetFontSize(9).SetBorder(
                        new SolidBorder(ColorConstants.BLACK, 0.5f)));
                }
            }
        }

        protected internal class MyEventHandler : IEventHandler {
            public virtual void HandleEvent(Event @event) {
                PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
                PdfDocument pdfDoc = docEvent.GetDocument();
                PdfPage page = docEvent.GetPage();
                int pageNumber = pdfDoc.GetPageNumber(page);
                Rectangle pageSize = page.GetPageSize();
                PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
                //Set background
                Color limeColor = new DeviceCmyk(0.208f, 0, 0.584f, 0);
                Color blueColor = new DeviceCmyk(0.445f, 0.0546f, 0, 0.0667f);
                pdfCanvas.SaveState().SetFillColor(pageNumber % 2 == 1 ? limeColor : blueColor).Rectangle(pageSize.GetLeft
                    (), pageSize.GetBottom(), pageSize.GetWidth(), pageSize.GetHeight()).Fill().RestoreState();
                //Add header and footer
                pdfCanvas.BeginText().SetFontAndSize(C03E03_UFO.helvetica, 9).MoveText(pageSize.GetWidth() / 2 - 60, pageSize
                    .GetTop() - 20).ShowText("THE TRUTH IS OUT THERE").MoveText(60, -pageSize.GetTop() + 30).ShowText(pageNumber
                    .ToString()).EndText();
                //Add watermark
                iText.Layout.Canvas canvas = new iText.Layout.Canvas(pdfCanvas, page.GetPageSize());
                canvas.SetFontColor(ColorConstants.WHITE);
                canvas.SetProperty(Property.FONT_SIZE, UnitValue.CreatePointValue(60));
                canvas.SetProperty(Property.FONT, C03E03_UFO.helveticaBold);
                canvas.ShowTextAligned(new Paragraph("CONFIDENTIAL"), 298, 421, pdfDoc.GetPageNumber(page), TextAlignment.
                    CENTER, VerticalAlignment.MIDDLE, 45);
                pdfCanvas.Release();
            }

            internal MyEventHandler(C03E03_UFO _enclosing) {
                this._enclosing = _enclosing;
            }

            private readonly C03E03_UFO _enclosing;
        }
    }
}
JavaScript errors detected

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

If this problem persists, please contact our support.