iText pdf library
Website search

Adding backgrounds using page events

Examples written in answer to questions such as:

PageBackgrounds.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
/*
    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/30211043/change-the-color-of-pdf-pages-alternatively-using-itext-pdf-in-java
 */
package com.itextpdf.samples.sandbox.events;
 
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
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.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
 
import java.io.File;
import java.util.ArrayList;
import java.util.List;
 
public class PageBackgrounds {
    public static final String DEST = "./target/sandbox/events/page_backgrounds.pdf";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
 
        new PageBackgrounds().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, new PageBackgroundsEventHandler());
        Document doc = new Document(pdfDoc);
 
        doc.add(new Paragraph("Prime Numbers"));
        doc.add(new AreaBreak());
        doc.add(new Paragraph("An overview"));
        doc.add(new AreaBreak());
        for (int i = 2; i < 301; i++) {
            List<Integer> factors = getFactors(i);
            if (factors.size() == 1) {
                doc.add(new Paragraph("This is a prime number!"));
            }
 
            for (int factor : factors) {
                doc.add(new Paragraph("Factor: " + factor));
            }
 
            if (300 != i) {
                doc.add(new AreaBreak());
            }
        }
 
        doc.close();
    }
 
    private static List<Integer> getFactors(int n) {
        List<Integer> factors = new ArrayList<>();
        for (int i = 2; i <= n; i++) {
            while (n % i == 0) {
                factors.add(i);
                n /= i;
            }
        }
 
        return factors;
    }
 
    private static class PageBackgroundsEventHandler implements IEventHandler {
        @Override
        public void handleEvent(Event currentEvent) {
            PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
            PdfPage page = docEvent.getPage();
 
            int pageNumber = docEvent.getDocument().getNumberOfPages();
 
            // Background color will be applied to the first page and all even pages
            if (pageNumber % 2 == 1 && pageNumber != 1) {
                return;
            }
 
            PdfCanvas canvas = new PdfCanvas(page);
            Rectangle rect = page.getPageSize();
            canvas
                    .saveState()
                    .setFillColor(pageNumber < 3 ? ColorConstants.BLUE : ColorConstants.LIGHT_GRAY)
                    .rectangle(rect)
                    .fillStroke()
                    .restoreState();
        }
    }
}
PageBorder.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
/*
    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/25749828/how-to-draw-border-for-whole-pdf-pages-using-itext-library-5-5-2
 */
package com.itextpdf.samples.sandbox.events;
 
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
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.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
 
import java.io.File;
import java.util.ArrayList;
import java.util.List;
 
public class PageBorder {
    public static final String DEST = "./target/sandbox/events/page_border.pdf";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
 
        new PageBorder().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, new PageBorderEventHandler());
        Document doc = new Document(pdfDoc);
 
        for (int i = 2; i < 301; i++) {
            List<Integer> factors = getFactors(i);
            if (factors.size() == 1) {
                doc.add(new Paragraph("This is a prime number!"));
            }
 
            for (int factor : factors) {
                doc.add(new Paragraph("Factor: " + factor));
            }
 
            if (300 != i) {
                doc.add(new AreaBreak());
            }
        }
 
        doc.close();
    }
 
    private static List<Integer> getFactors(int n) {
        List<Integer> factors = new ArrayList<>();
        for (int i = 2; i <= n; i++) {
            while (n % i == 0) {
                factors.add(i);
                n /= i;
            }
        }
 
        return factors;
    }
 
 
    private static class PageBorderEventHandler implements IEventHandler {
        @Override
        public void handleEvent(Event currentEvent) {
            PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
            PdfCanvas canvas = new PdfCanvas(docEvent.getPage());
            Rectangle rect = docEvent.getPage().getPageSize();
 
            canvas
                    .setLineWidth(5)
                    .setStrokeColor(ColorConstants.RED)
                    .rectangle(rect)
                    .stroke();
        }
    }
}
PageBackgrounds.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
/*
    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.Collections.Generic;
using System.IO;
using iText.Kernel.Colors;
using iText.Kernel.Events;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout;
using iText.Layout.Element;
 
namespace iText.Samples.Sandbox.Events
{
    public class PageBackgrounds
    {
        public static readonly String DEST = "results/sandbox/events/page_backgrounds.pdf";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new PageBackgrounds().ManipulatePdf(DEST);
        }
 
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            pdfDoc.AddEventHandler(PdfDocumentEvent.START_PAGE, new PageBackgroundsEventHandler());
            Document doc = new Document(pdfDoc);
 
            doc.Add(new Paragraph("Prime Numbers"));
            doc.Add(new AreaBreak());
            doc.Add(new Paragraph("An overview"));
            doc.Add(new AreaBreak());
            for (int i = 2; i < 301; i++)
            {
                List<int> factors = GetFactors(i);
                if (factors.Count == 1)
                {
                    doc.Add(new Paragraph("This is a prime number!"));
                }
 
                foreach (int factor in factors)
                {
                    doc.Add(new Paragraph("Factor: " + factor));
                }
 
                if (300 != i)
                {
                    doc.Add(new AreaBreak());
                }
            }
 
            doc.Close();
        }
 
        private static List<int> GetFactors(int n)
        {
            List<int> factors = new List<int>();
            for (int i = 2; i <= n; i++)
            {
                while (n % i == 0)
                {
                    factors.Add(i);
                    n /= i;
                }
            }
 
            return factors;
        }
 
        private class PageBackgroundsEventHandler : IEventHandler
        {
            public void HandleEvent(Event currentEvent)
            {
                PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
                PdfPage page = docEvent.GetPage();
 
                int pageNumber = docEvent.GetDocument().GetNumberOfPages();
 
                // Background color will be applied to the first page and all even pages
                if (pageNumber % 2 == 1 && pageNumber != 1)
                {
                    return;
                }
 
                PdfCanvas canvas = new PdfCanvas(page);
                Rectangle rect = page.GetPageSize();
                canvas
                    .SaveState()
                    .SetFillColor(pageNumber < 3 ? ColorConstants.BLUE : ColorConstants.LIGHT_GRAY)
                    .Rectangle(rect)
                    .FillStroke()
                    .RestoreState();
            }
        }
    }
}
PageBorder.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
/*
    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.Collections.Generic;
using System.IO;
using iText.Kernel.Colors;
using iText.Kernel.Events;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout;
using iText.Layout.Element;
 
namespace iText.Samples.Sandbox.Events
{
    public class PageBorder
    {
        public static readonly String DEST = "results/sandbox/events/page_border.pdf";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new PageBorder().ManipulatePdf(DEST);
        }
 
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            pdfDoc.AddEventHandler(PdfDocumentEvent.START_PAGE, new PageBorderEventHandler());
            Document doc = new Document(pdfDoc);
 
            for (int i = 2; i < 301; i++)
            {
                IList<int> factors = GetFactors(i);
                if (factors.Count == 1)
                {
                    doc.Add(new Paragraph("This is a prime number!"));
                }
 
                foreach (int factor in factors)
                {
                    doc.Add(new Paragraph("Factor: " + factor));
                }
 
                if (300 != i)
                {
                    doc.Add(new AreaBreak());
                }
            }
 
            doc.Close();
        }
 
        private static IList<int> GetFactors(int n)
        {
            IList<int> factors = new List<int>();
            for (int i = 2; i <= n; i++)
            {
                while (n % i == 0)
                {
                    factors.Add(i);
                    n /= i;
                }
            }
 
            return factors;
        }
 
        private class PageBorderEventHandler : IEventHandler
        {
            public void HandleEvent(Event currentEvent)
            {
                PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
                PdfCanvas canvas = new PdfCanvas(docEvent.GetPage());
                Rectangle rect = docEvent.GetPage().GetPageSize();
 
                canvas
                    .SetLineWidth(5)
                    .SetStrokeColor(ColorConstants.RED)
                    .Rectangle(rect)
                    .Stroke();
            }
        }
    }
}

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


Tags
background

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