iText pdf library
Website search

Page numbers and PDF/A

This example was written in answer to the question How to add a page number in the header of a PDF/A Level A file?

PdfA1a.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2020 iText Group NV
    Authors: iText Software.
 
    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
/**
 * Example written by Bruno Lowagie in answer to:
 * http://stackoverflow.com/questions/27500586/itext-page-number-in-header-within-pdf-a
 */
package com.itextpdf.samples.sandbox.pdfa;
 
import com.itextpdf.io.font.PdfEncodings;
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.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.PdfAConformanceLevel;
import com.itextpdf.kernel.pdf.PdfOutputIntent;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfDate;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.tagging.StandardRoles;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.kernel.xmp.XMPException;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.pdfa.PdfADocument;
 
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
 
public class PdfA1a {
    public static final String DEST = "./target/sandbox/pdfa/pdf_a_1a.pdf";
 
    public static final String BOLD = "./src/test/resources/font/OpenSans-Bold.ttf";
 
    public static final String DATA = "./src/test/resources/data/united_states.csv";
 
    public static final String FONT = "./src/test/resources/font/OpenSans-Regular.ttf";
 
    protected PdfFormXObject template;
 
    protected Image total;
 
    protected PdfFont font;
 
    protected PdfFont bold;
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
 
        new PdfA1a().manipulatePdf(DEST);
    }
 
    public void manipulatePdf(String dest) throws IOException, XMPException {
        font = PdfFontFactory.createFont(FONT, PdfEncodings.IDENTITY_H);
        bold = PdfFontFactory.createFont(BOLD, PdfEncodings.IDENTITY_H);
 
        FileInputStream fileInputStream = new FileInputStream("./src/test/resources/data/sRGB_CS_profile.icm");
 
        PdfADocument pdfDoc = new PdfADocument(new PdfWriter(dest), PdfAConformanceLevel.PDF_A_1A,
                new PdfOutputIntent("Custom", "",
                        null, "sRGB IEC61966-2.1", fileInputStream));
 
        Document document = new Document(pdfDoc, PageSize.A4.rotate());
        pdfDoc
                .setTagged()
                .getCatalog()
                .setLang(new PdfString("en-us"));
 
        template = new PdfFormXObject(new Rectangle(795, 575, 30, 30));
        PdfCanvas canvas = new PdfCanvas(template, pdfDoc);
 
        total = new Image(template);
        total.getAccessibilityProperties().setRole(StandardRoles.ARTIFACT);
 
        // Creates a header for every page in the document
        pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, new HeaderHandler());
 
        PdfDictionary parameters = new PdfDictionary();
        parameters.put(PdfName.ModDate, new PdfDate().getPdfObject());
 
        Table table = new Table(UnitValue.createPercentArray(
                new float[]{4, 1, 3, 4, 3, 3, 3, 3, 1})).useAllAvailableWidth();
 
        BufferedReader br = new BufferedReader(new FileReader(DATA));
 
        // Reads content of csv file
        String line = br.readLine();
        process(table, line, bold, 10, true);
 
        while ((line = br.readLine()) != null) {
            process(table, line, font, 10, false);
        }
 
        br.close();
 
        document.add(table);
 
        canvas.beginText();
        canvas.setFontAndSize(bold, 12);
        canvas.moveText(795, 575);
        canvas.showText(Integer.toString(pdfDoc.getNumberOfPages()));
        canvas.endText();
        canvas.stroke();
 
        document.close();
    }
 
    public void process(Table table, String line, PdfFont font, int fontSize, boolean isHeader) {
 
        // Parses csv string line with specified delimiter
        StringTokenizer tokenizer = new StringTokenizer(line, ";");
 
        while (tokenizer.hasMoreTokens()) {
            Paragraph content = new Paragraph(tokenizer.nextToken()).setFont(font).setFontSize(fontSize);
 
            if (isHeader) {
                table.addHeaderCell(content);
            } else {
                table.addCell(content);
            }
        }
    }
 
 
    public class HeaderHandler implements IEventHandler {
        @Override
        public void handleEvent(Event event) {
            PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
            PdfPage page = docEvent.getPage();
            int pageNum = docEvent.getDocument().getPageNumber(page);
 
            PdfCanvas canvas = new PdfCanvas(page);
 
            // Creates header text content
            canvas.beginText();
            canvas.setFontAndSize(font, 12);
            canvas.beginMarkedContent(PdfName.Artifact);
            canvas.moveText(34, 575);
            canvas.showText("Test");
            canvas.moveText(703, 0);
            canvas.showText(String.format("Page %d of", pageNum));
            canvas.endText();
            canvas.stroke();
            canvas.addXObject(template, 0, 0);
            canvas.endMarkedContent();
            canvas.release();
        }
    }
}
PdfA1a.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2020 iText Group NV
Authors: iText Software.
 
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
 
using System;
using System.IO;
using iText.IO.Font;
using iText.IO.Util;
using iText.Kernel.Events;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Tagging;
using iText.Kernel.Pdf.Xobject;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.Pdfa;
 
namespace iText.Samples.Sandbox.Pdfa
{
    public class PdfA1a
    {
        public static readonly string DEST = "results/sandbox//pdfa/pdf_a_1a.pdf";
 
        public static readonly String BOLD = "../../resources/font/OpenSans-Bold.ttf";
 
        public static readonly String DATA = "../../resources/data/united_states.csv";
 
        public static readonly String FONT = "../../resources/font/OpenSans-Regular.ttf";
 
        private PdfFormXObject template;
 
        private Image total;
 
        private PdfFont font;
 
        private PdfFont bold;
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new PdfA1a().ManipulatePdf(DEST);
        }
 
        private void ManipulatePdf(String dest)
        {
            font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H);
            bold = PdfFontFactory.CreateFont(BOLD, PdfEncodings.IDENTITY_H);
 
            FileStream fileStream =
                new FileStream("../../resources/data/sRGB_CS_profile.icm", FileMode.Open, FileAccess.Read);
 
            PdfADocument pdfDoc = new PdfADocument(new PdfWriter(dest), PdfAConformanceLevel.PDF_A_1A,
                new PdfOutputIntent("Custom", "",
                    null, "sRGB IEC61966-2.1", fileStream));
 
            Document document = new Document(pdfDoc, PageSize.A4.Rotate());
            pdfDoc
                .SetTagged()
                .GetCatalog()
                .SetLang(new PdfString("en-us"));
 
            template = new PdfFormXObject(new Rectangle(795, 575, 30, 30));
            PdfCanvas canvas = new PdfCanvas(template, pdfDoc);
 
            total = new Image(template);
            total.GetAccessibilityProperties().SetRole(StandardRoles.ARTIFACT);
 
            // Creates a header for every page in the document
            pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new HeaderHandler(this));
 
            PdfDictionary parameters = new PdfDictionary();
            parameters.Put(PdfName.ModDate, new PdfDate().GetPdfObject());
 
            Table table = new Table(UnitValue.CreatePercentArray(
                new float[] {4, 1, 3, 4, 3, 3, 3, 3, 1})).UseAllAvailableWidth();
 
            StreamReader br = new StreamReader(DATA);
 
            // Reads content of csv file
            String line = br.ReadLine();
            Process(table, line, bold, 10, true);
 
            while ((line = br.ReadLine()) != null)
            {
                Process(table, line, font, 10, false);
            }
 
            br.Close();
 
            document.Add(table);
 
            canvas.BeginText();
            canvas.SetFontAndSize(bold, 12);
            canvas.MoveText(795, 575);
            canvas.ShowText(pdfDoc.GetNumberOfPages().ToString());
            canvas.EndText();
            canvas.Stroke();
 
            document.Close();
        }
 
        private void Process(Table table, String line, PdfFont currentFont, int fontSize, bool isHeader)
        {
            // Parses csv string line with specified delimiter
            StringTokenizer tokenizer = new StringTokenizer(line, ";");
 
            while (tokenizer.HasMoreTokens())
            {
                Paragraph content = new Paragraph(tokenizer.NextToken()).SetFont(currentFont).SetFontSize(fontSize);
 
                if (isHeader)
                {
                    table.AddHeaderCell(content);
                }
                else
                {
                    table.AddCell(content);
                }
            }
        }
 
        private class HeaderHandler : IEventHandler
        {
            private readonly PdfA1a enclosing;
 
            public HeaderHandler(PdfA1a enclosing)
            {
                this.enclosing = enclosing;
            }
 
            public virtual void HandleEvent(Event currentEvent)
            {
                PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
                PdfPage page = docEvent.GetPage();
                int pageNum = docEvent.GetDocument().GetPageNumber(page);
 
                PdfCanvas canvas = new PdfCanvas(page);
 
                // Creates header text content
                canvas.BeginText();
                canvas.SetFontAndSize(enclosing.font, 12);
                canvas.BeginMarkedContent(PdfName.Artifact);
                canvas.MoveText(34, 575);
                canvas.ShowText("Test");
                canvas.MoveText(703, 0);
                canvas.ShowText(String.Format("Page {0:d} of", pageNum));
                canvas.EndText();
                canvas.Stroke();
                canvas.AddXObject(enclosing.template, 0, 0);
                canvas.EndMarkedContent();
                canvas.Release();
            }
        }
    }
}

Click the following link to see the legacy example for iText 5. Except for security fixes, iText 5 is no longer being developed.



Contact

Still have questions? 

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

Contact us
Stay updated

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

Subscribe Now