iText pdf library
Website search

Adding images to a table

AddOverlappingImage.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 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 the following question:
 * http://stackoverflow.com/questions/22094289/itext-precisely-position-an-image-on-top-of-a-pdfptable
 */
package com.itextpdf.samples.sandbox.tables;
 
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.layout.renderer.DrawContext;
import com.itextpdf.layout.renderer.IRenderer;
import com.itextpdf.layout.renderer.TableRenderer;
 
import java.io.File;
 
public class AddOverlappingImage {
    public static final String DEST = "./target/sandbox/tables/add_overlapping_image.pdf";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new AddOverlappingImage().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
 
        Table table = new Table(UnitValue.createPercentArray(5)).useAllAvailableWidth();
        table.setNextRenderer(new OverlappingImageTableRenderer(table, new Table.RowRange(0, 25),
                ImageDataFactory.create("./src/test/resources/img/hero.jpg")));
        Cell cell;
        for (int r = 'A'; r <= 'Z'; r++) {
            for (int c = 1; c <= 5; c++) {
                cell = new Cell();
                cell.add(new Paragraph(String.valueOf((char) r) + String.valueOf(c)));
                table.addCell(cell);
            }
        }
        doc.add(table);
 
        doc.close();
    }
 
 
    private class OverlappingImageTableRenderer extends TableRenderer {
        private ImageData image;
 
        public OverlappingImageTableRenderer(Table modelElement, Table.RowRange rowRange, ImageData img) {
            super(modelElement, rowRange);
            this.image = img;
        }
 
        public OverlappingImageTableRenderer(Table modelElement, ImageData img) {
            super(modelElement);
            this.image = img;
        }
 
        @Override
        public void drawChildren(DrawContext drawContext) {
            super.drawChildren(drawContext);
            float x = Math.max(this.getOccupiedAreaBBox().getX() +
                    this.getOccupiedAreaBBox().getWidth() / 3 - image.getWidth(), 0);
            float y = Math.max(this.getOccupiedAreaBBox().getY() +
                    this.getOccupiedAreaBBox().getHeight() / 3 - image.getHeight(), 0);
            drawContext.getCanvas().addImage(image, x, y, false);
        }
 
        @Override
        public IRenderer getNextRenderer() {
            return new OverlappingImageTableRenderer((Table) modelElement, image);
        }
    }
}
IconDescriptionTable.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 iText Group NV
    Authors: iText Software.
 
    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
/**
 * This example was written by Bruno Lowagie in answer to the following question:
 * http://stackoverflow.com/questions/23375618/how-to-add-an-icon-to-an-itext-pdfpcell
 */
package com.itextpdf.samples.sandbox.tables;
 
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;
 
import java.io.File;
 
public class IconDescriptionTable {
    public static final String DEST = "./target/sandbox/tables/icon_description_table.pdf";
    public static final String IMG = "./src/test/resources/img/bulb.gif";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new IconDescriptionTable().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
 
        Table table = new Table(UnitValue.createPercentArray(new float[]{10, 90}));
        Image img = new Image(ImageDataFactory.create(IMG));
        table.addCell(img.setAutoScale(true));
        table.addCell("A light bulb icon");
        doc.add(table);
 
        doc.close();
    }
}
ImageNextToText.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 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/25780258/how-to-display-image-and-text-beside-each-other-itext
 */
package com.itextpdf.samples.sandbox.tables;
 
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.layout.property.VerticalAlignment;
 
import java.io.File;
import java.net.MalformedURLException;
 
public class ImageNextToText {
    public static final String DEST = "./target/sandbox/tables/image_next_to_text.pdf";
    public static final String IMG1 = "./src/test/resources/img/javaone2013.jpg";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new ImageNextToText().manipulatePdf(DEST);
    }
 
    public static Cell createImageCell(String path) throws MalformedURLException {
        Image img = new Image(ImageDataFactory.create(path));
        img.setWidth(UnitValue.createPercentValue(100));
        Cell cell = new Cell().add(img);
        cell.setBorder(null);
        return cell;
    }
 
    public static Cell createTextCell(String text) {
        Cell cell = new Cell();
        Paragraph p = new Paragraph(text);
        p.setTextAlignment(TextAlignment.RIGHT);
        cell.add(p).setVerticalAlignment(VerticalAlignment.BOTTOM);
        cell.setBorder(Border.NO_BORDER);
        return cell;
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
        Table table = new Table(UnitValue.createPercentArray(new float[]{1, 2}));
        table.addCell(createImageCell(IMG1));
        table.addCell(createTextCell("This picture was taken at Java One.\nIt shows the iText crew at Java One in 2013."));
        doc.add(table);
 
        doc.close();
    }
}
ImagesInChunkInCell.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 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 the following question:
 * http://stackoverflow.com/questions/32130219/itext-list-of-images-in-a-cell
 */
package com.itextpdf.samples.sandbox.tables;
 
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
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.element.Text;
 
import java.io.File;
 
public class ImagesInChunkInCell {
    public static final String DEST = "./target/sandbox/tables/images_in_chunk_in_cell.pdf";
    public static final String IMG = "./src/test/resources/img/bulb.gif";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new ImagesInChunkInCell().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
        Image image = new Image(ImageDataFactory.create(IMG));
        Table table = new Table(new float[]{120});
        Paragraph listOfDots = new Paragraph();
        for (int i = 0; i < 40; i++) {
            listOfDots.add(image);
            listOfDots.add(new Text(" "));
        }
        table.addCell(listOfDots);
        doc.add(table);
        doc.close();
    }
}
ImagesNextToEachOther.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 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/19700549/itextsharp-images-are-not-coming-next-to-one-another
 */
package com.itextpdf.samples.sandbox.tables;
 
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;
 
import java.io.File;
import java.net.MalformedURLException;
 
public class ImagesNextToEachOther {
    public static final String DEST = "./target/sandbox/tables/image_next_to_each_other.pdf";
    public static final String IMG1 = "./src/test/resources/img/javaone2013.jpg";
    public static final String IMG2 = "./src/test/resources/img/berlin2013.jpg";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new ImagesNextToEachOther().manipulatePdf(DEST);
    }
 
    public static Cell createImageCell(String path) throws MalformedURLException {
        Image img = new Image(ImageDataFactory.create(path));
        return new Cell().add(img.setAutoScale(true).setWidth(UnitValue.createPercentValue(100)));
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
 
        Table table = new Table(UnitValue.createPercentArray(2)).useAllAvailableWidth();
        table.addCell(createImageCell(IMG1));
        table.addCell(createImageCell(IMG2));
        doc.add(table);
 
        doc.close();
    }
}
MultipleImagesInCell.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 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/33603296/how-to-add-two-images-in-one-cell-in-itext
 */
package com.itextpdf.samples.sandbox.tables;
 
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Cell;
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 java.io.File;
 
public class MultipleImagesInCell {
    public static final String DEST
            = "./target/sandbox/tables/multiple_images_in_cell.pdf";
    public static final String IMG1
            = "./src/test/resources/img/brasil.png";
    public static final String IMG2
            = "./src/test/resources/img/dog.bmp";
    public static final String IMG3
            = "./src/test/resources/img/fox.bmp";
 
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new MultipleImagesInCell().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
 
        Image img1 = new Image(ImageDataFactory.create(IMG1));
        Image img2 = new Image(ImageDataFactory.create(IMG2));
        Image img3 = new Image(ImageDataFactory.create(IMG3));
 
        Table table = new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth();
        table.setWidth(UnitValue.createPercentValue(50));
        table.addCell("Different images, one after the other vertically:");
        Cell cell = new Cell();
 
        // There's no image autoscaling by default
        cell.add(img1.setAutoScale(true));
        cell.add(img2.setAutoScale(true));
        cell.add(img3.setAutoScale(true));
        table.addCell(cell);
        doc.add(table);
        doc.add(new AreaBreak());
 
        // In the snippet after this autoscaling is not needed
        // Notice that we do not need to create new Image instances since the images had been already flushed
        img1.setAutoScale(false);
        img2.setAutoScale(false);
        img3.setAutoScale(false);
 
        table = new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth();
        table.addCell("Different images, one after the other vertically, but scaled:");
        cell = new Cell();
        img1.setWidth(UnitValue.createPercentValue(20));
        cell.add(img1);
        img2.setWidth(UnitValue.createPercentValue(20));
        cell.add(img2);
        img3.setWidth(UnitValue.createPercentValue(20));
        cell.add(img3);
        table.addCell(cell);
        table.addCell("Different images, one after the other horizontally:");
 
        // Notice that the table is not flushed yet so it's strictly forbidden to change image properties yet
        img1 = new Image(ImageDataFactory.create(IMG1));
        img2 = new Image(ImageDataFactory.create(IMG2));
        img3 = new Image(ImageDataFactory.create(IMG3));
 
        Paragraph p = new Paragraph();
        img1.scale(0.3f, 0.3f);
        p.add(img1);
        p.add(img2);
        p.add(img3);
        table.addCell(p);
        table.addCell("Text and images (mixed):");
 
        img2 = new Image(ImageDataFactory.create(IMG2));
        img3 = new Image(ImageDataFactory.create(IMG3));
 
        p = new Paragraph("The quick brown ");
        p.add(img3);
        p.add(" jumps over the lazy ");
        p.add(img2);
        cell = new Cell();
        cell.add(p);
        table.addCell(cell);
 
        doc.add(table);
 
        doc.close();
    }
}
MultipleImagesInTable.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 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/34303448
 */
package com.itextpdf.samples.sandbox.tables;
 
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;
 
import java.io.File;
 
public class MultipleImagesInTable {
    public static final String DEST
            = "./target/sandbox/tables/multiple_images_in_table.pdf";
    public static final String IMG1
            = "./src/test/resources/img/brasil.png";
    public static final String IMG2
            = "./src/test/resources/img/dog.bmp";
    public static final String IMG3
            = "./src/test/resources/img/fox.bmp";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new MultipleImagesInTable().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
 
        Image img1 = new Image(ImageDataFactory.create(IMG1));
        Image img2 = new Image(ImageDataFactory.create(IMG2));
        Image img3 = new Image(ImageDataFactory.create(IMG3));
 
        Table table = new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth();
        table.setWidth(UnitValue.createPercentValue(20));
 
        img1.setAutoScale(true);
        img2.setAutoScale(true);
        img3.setAutoScale(true);
 
        table.addCell(img1);
        table.addCell("Brazil");
        table.addCell(img2);
        table.addCell("Dog");
        table.addCell(img3);
        table.addCell("Fox");
 
        doc.add(table);
 
        doc.close();
    }
}
PositionContentInCell.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 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 the following question:
 * http://stackoverflow.com/questions/31169268/cell-background-image-with-text-itextsharp
 */
 
package com.itextpdf.samples.sandbox.tables;
 
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.Leading;
import com.itextpdf.layout.property.Property;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DocumentRenderer;
import com.itextpdf.layout.renderer.DrawContext;
 
import java.io.File;
 
public class PositionContentInCell {
    public static final String DEST = "./target/sandbox/tables/position_content_in_cell.pdf";
    public static final String IMG = "./src/test/resources/img/info.png";
 
    public enum POSITION {TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT}
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new PositionContentInCell().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        // 1. Create a Document which contains a table:
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
        Table table = new Table(UnitValue.createPercentArray(2)).useAllAvailableWidth();
        Cell cell1 = new Cell();
        Cell cell2 = new Cell();
        Cell cell3 = new Cell();
        Cell cell4 = new Cell();
        // 2. Inside that table, make each cell with specific height:
        cell1.setHeight(50);
        cell2.setHeight(50);
        cell3.setHeight(50);
        cell4.setHeight(50);
        // 3. Each cell has the same background image
        // 4. Add text in front of the image at specific position
        cell1.setNextRenderer(new ImageAndPositionRenderer(cell1,
                new Image(ImageDataFactory.create(IMG)), "Top left", POSITION.TOP_LEFT));
        cell2.setNextRenderer(new ImageAndPositionRenderer(cell2,
                new Image(ImageDataFactory.create(IMG)), "Top right", POSITION.TOP_RIGHT));
        cell3.setNextRenderer(new ImageAndPositionRenderer(cell3,
                new Image(ImageDataFactory.create(IMG)), "Bottom left", POSITION.BOTTOM_LEFT));
        cell4.setNextRenderer(new ImageAndPositionRenderer(cell4,
                new Image(ImageDataFactory.create(IMG)), "Bottom right", POSITION.BOTTOM_RIGHT));
        // Wrap it all up!
        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);
        table.addCell(cell4);
        doc.add(table);
 
        doc.close();
    }
 
 
    private class ImageAndPositionRenderer extends CellRenderer {
        private Image img;
        private String content;
        private POSITION position;
 
        public ImageAndPositionRenderer(Cell modelElement, Image img, String content, POSITION position) {
            super(modelElement);
            this.img = img;
            this.content = content;
            this.position = position;
        }
 
        @Override
        public void draw(DrawContext drawContext) {
            super.draw(drawContext);
            img.scaleToFit(getOccupiedAreaBBox().getWidth(), getOccupiedAreaBBox().getHeight());
 
            drawContext.getCanvas().addXObject(img.getXObject(),
                    getOccupiedAreaBBox().getX() +
                            (getOccupiedAreaBBox().getWidth()
                                    - img.getImageWidth() * (float) img.getProperty(Property.HORIZONTAL_SCALING)) / 2,
                    getOccupiedAreaBBox().getY() +
                            (getOccupiedAreaBBox().getHeight()
                                    - img.getImageHeight() * (float) img.getProperty(Property.VERTICAL_SCALING)) / 2,
                    img.getImageWidth() * (float) img.getProperty(Property.HORIZONTAL_SCALING));
            drawContext.getCanvas().stroke();
 
            Paragraph p = new Paragraph(content);
            Leading leading = p.getDefaultProperty(Property.LEADING);
            UnitValue defaultFontSizeUV = new DocumentRenderer(new Document(drawContext.getDocument())).getPropertyAsUnitValue(Property.FONT_SIZE);
            float defaultFontSize = defaultFontSizeUV.isPointValue() ? defaultFontSizeUV.getValue() : 12f;
            float x;
            float y;
            TextAlignment alignment;
            switch (position) {
                case TOP_LEFT:
                    x = getOccupiedAreaBBox().getLeft() + 3;
                    y = getOccupiedAreaBBox().getTop() - defaultFontSize * leading.getValue();
                    alignment = TextAlignment.LEFT;
                    break;
                case TOP_RIGHT:
                    x = getOccupiedAreaBBox().getRight() - 3;
                    y = getOccupiedAreaBBox().getTop() - defaultFontSize * leading.getValue();
                    alignment = TextAlignment.RIGHT;
                    break;
                case BOTTOM_LEFT:
                    x = getOccupiedAreaBBox().getLeft() + 3;
                    y = getOccupiedAreaBBox().getBottom() + 3;
                    alignment = TextAlignment.LEFT;
                    break;
                case BOTTOM_RIGHT:
                    x = getOccupiedAreaBBox().getRight() - 3;
                    y = getOccupiedAreaBBox().getBottom() + 3;
                    alignment = TextAlignment.RIGHT;
                    break;
                default:
                    x = 0;
                    y = 0;
                    alignment = TextAlignment.CENTER;
            }
            new Canvas(drawContext.getCanvas(), drawContext.getDocument(), getOccupiedAreaBBox()).showTextAligned(p, x, y, alignment);
        }
    }
}
PositionContentInCell2.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 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 the following question:
 * http://stackoverflow.com/questions/31169268/cell-background-image-with-text-itextsharp
 */
package com.itextpdf.samples.sandbox.tables;
 
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.Property;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DrawContext;
 
import java.io.File;
 
public class PositionContentInCell2 {
    public static final String DEST = "./target/sandbox/tables/position_content_in_cell2.pdf";
    public static final String IMG = "./src/test/resources/img/info.png";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new PositionContentInCell2().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        // 1. Create a Document which contains a table:
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
        Table table = new Table(UnitValue.createPercentArray(2)).useAllAvailableWidth();
        Cell cell1 = new Cell();
        Cell cell2 = new Cell();
        Cell cell3 = new Cell();
        Cell cell4 = new Cell();
        Cell cell5 = new Cell();
        Cell cell6 = new Cell();
        Cell cell7 = new Cell();
        Cell cell8 = new Cell();
        // 2. Inside that table, make each cell with specific height:
        cell1.setHeight(50);
        cell2.setHeight(50);
        cell3.setHeight(50);
        cell4.setHeight(50);
        cell5.setHeight(50);
        cell6.setHeight(50);
        cell7.setHeight(50);
        cell8.setHeight(50);
        // 3. Each cell has the same background image
        // 4. Add text in front of the image at specific position
        cell1.setNextRenderer(new ImageAndPositionRenderer(cell1, 0, 1,
                new Image(ImageDataFactory.create(IMG)), "Top left", TextAlignment.LEFT));
        cell2.setNextRenderer(new ImageAndPositionRenderer(cell2, 1, 1,
                new Image(ImageDataFactory.create(IMG)), "Top right", TextAlignment.RIGHT));
        cell3.setNextRenderer(new ImageAndPositionRenderer(cell3, 0.5f, 1,
                new Image(ImageDataFactory.create(IMG)), "Top center", TextAlignment.CENTER));
        cell4.setNextRenderer(new ImageAndPositionRenderer(cell4, 0.5f, 0,
                new Image(ImageDataFactory.create(IMG)), "Bottom center", TextAlignment.CENTER));
        cell5.setNextRenderer(new ImageAndPositionRenderer(cell5, 0.5f, 0.5f,
                new Image(ImageDataFactory.create(IMG)), "Middle center", TextAlignment.CENTER));
        cell6.setNextRenderer(new ImageAndPositionRenderer(cell6, 0.5f, 0.5f,
                new Image(ImageDataFactory.create(IMG)), "Middle center", TextAlignment.CENTER));
        cell7.setNextRenderer(new ImageAndPositionRenderer(cell7, 0, 0,
                new Image(ImageDataFactory.create(IMG)), "Bottom left", TextAlignment.LEFT));
        cell8.setNextRenderer(new ImageAndPositionRenderer(cell8, 1, 0,
                new Image(ImageDataFactory.create(IMG)), "Bottom right", TextAlignment.RIGHT));
        // Wrap it all up!
        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);
        table.addCell(cell4);
        table.addCell(cell5);
        table.addCell(cell6);
        table.addCell(cell7);
        table.addCell(cell8);
        doc.add(table);
 
        doc.close();
    }
 
 
    private class ImageAndPositionRenderer extends CellRenderer {
        private Image img;
        private String content;
        private TextAlignment alignment;
        private float wPct;
        private float hPct;
 
        public ImageAndPositionRenderer(Cell modelElement, float wPct, float hPct,
                                        Image img, String content, TextAlignment alignment) {
            super(modelElement);
            this.img = img;
            this.content = content;
            this.alignment = alignment;
            this.wPct = wPct;
            this.hPct = hPct;
        }
 
        @Override
        public void draw(DrawContext drawContext) {
            super.draw(drawContext);
 
            drawContext.getCanvas().addXObject(img.getXObject(), getOccupiedAreaBBox());
            drawContext.getCanvas().stroke();
 
            UnitValue fontSizeUV = getPropertyAsUnitValue(Property.FONT_SIZE);
            float x = getOccupiedAreaBBox().getX() + wPct * getOccupiedAreaBBox().getWidth();
            float y = getOccupiedAreaBBox().getY() + hPct * (getOccupiedAreaBBox().getHeight() - (fontSizeUV.isPointValue() ? fontSizeUV.getValue() : 12f)*1.5f);
            new Document(drawContext.getDocument()).showTextAligned(content, x, y, alignment);
 
        }
    }
}
SimpleTable8.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 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 the following question:
 * http://stackoverflow.com/questions/29752875/generate-pdf-from-java-code-that-dynamically-continue-file-template-with-itext
 */
package com.itextpdf.samples.sandbox.tables;
 
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;
 
import java.io.File;
 
public class SimpleTable8 {
    public static final String DEST = "./target/sandbox/tables/simple_table8.pdf";
    public static final String SRC = "./src/test/resources/pdfs/";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new SimpleTable8().manipulatePdf(DEST);
    }
 
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
 
        Table table = new Table(UnitValue.createPercentArray(3)).useAllAvailableWidth();
        PdfReader reader = new PdfReader(SRC + "header_test_file.pdf");
        PdfDocument srcDoc = new PdfDocument(reader);
        PdfFormXObject header = srcDoc.getFirstPage().copyAsFormXObject(pdfDoc);
        Cell cell = new Cell(1, 3).add(new Image(header).setWidth(UnitValue.createPercentValue(100)).setAutoScale(true));
        table.addCell(cell);
        for (int row = 1; row <= 50; row++) {
            for (int column = 1; column <= 3; column++) {
                table.addCell(String.format("row %s, column %s", row, column));
            }
        }
        reader = new PdfReader(SRC + "footer_test_file.pdf");
        srcDoc = new PdfDocument(reader);
        PdfFormXObject footer = srcDoc.getFirstPage().copyAsFormXObject(pdfDoc);
        cell = new Cell(1, 3).add(new Image(footer).setWidth(UnitValue.createPercentValue(100)).setAutoScale(true));
        table.addCell(cell);
        doc.add(table);
 
        doc.close();
    }
}
AddOverlappingImage.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
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2019 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.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.Layout.Renderer;
 
namespace iText.Samples.Sandbox.Tables
{
    public class AddOverlappingImage
    {
        public static readonly string DEST = "../../results/sandbox/tables/add_overlapping_image.pdf";
        
        public static void Main(String[] args) 
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new AddOverlappingImage().ManipulatePdf(DEST);
        }
        
        private void ManipulatePdf(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
 
            // By default column width is calculated automatically for the best fit.
            // useAllAvailableWidth() method set table to use the whole page's width while placing the content.
            Table table = new Table(UnitValue.CreatePercentArray(5)).UseAllAvailableWidth();
            
            // Adds drawn on a canvas image to the table
            table.SetNextRenderer(new OverlappingImageTableRenderer(table, new Table.RowRange(0, 25),
                ImageDataFactory.Create("../../resources/img/hero.jpg")));
 
            for (int r = 'A'; r <= 'Z'; r++) 
            {
                for (int c = 1; c <= 5; c++)
                {
                    Cell cell = new Cell();
                    cell.Add(new Paragraph(((char)r) + c.ToString()));
                    table.AddCell(cell);
                }
            }
 
            doc.Add(table);
 
            doc.Close();
        }
 
        private class OverlappingImageTableRenderer : TableRenderer
        {
            private ImageData image;
 
            public OverlappingImageTableRenderer(Table modelElement, Table.RowRange rowRange, ImageData img)
                : base(modelElement, rowRange)
            {
                image = img;
            }
 
            public OverlappingImageTableRenderer(Table modelElement, ImageData img)
                : base(modelElement)
            {
                image = img;
            }
 
        
        public override void DrawChildren(DrawContext drawContext)
        {
            base.DrawChildren(drawContext);
            
            float x = Math.Max(GetOccupiedAreaBBox().GetX() +
                    GetOccupiedAreaBBox().GetWidth() / 3 - image.GetWidth(), 0);
            float y = Math.Max(GetOccupiedAreaBBox().GetY() +
                    GetOccupiedAreaBBox().GetHeight() / 3 - image.GetHeight(), 0);
            
            drawContext.GetCanvas().AddImage(image, x, y, false);
        }
 
 
        public override IRenderer GetNextRenderer()
        {
            return new OverlappingImageTableRenderer((Table)modelElement, image);
        }
    }
}
 
}
IconDescriptionTable.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
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2019 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.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
 
namespace iText.Samples.Sandbox.Tables
{
    public class IconDescriptionTable
    {
        public static readonly string DEST = "../../results/sandbox/tables/icon_description_table.pdf";
 
        public static readonly string IMG = "../../resources/img/bulb.gif";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new IconDescriptionTable().ManipulatePdf(DEST);
        }
 
        private void ManipulatePdf(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
 
            Table table = new Table(UnitValue.CreatePercentArray(new float[] {10, 90}));
            Image img = new Image(ImageDataFactory.Create(IMG));
 
            // Width and height of image are set to autoscale
            table.AddCell(img.SetAutoScale(true));
            table.AddCell("A light bulb icon");
 
            doc.Add(table);
 
            doc.Close();
        }
    }
}
ImageNextToText.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
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2019 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.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Borders;
using iText.Layout.Element;
using iText.Layout.Properties;
 
namespace iText.Samples.Sandbox.Tables
{
    public class ImageNextToText
    {
        public static readonly string DEST = "../../results/sandbox/tables/image_next_to_text.pdf";
 
        public static readonly string IMG1 = "../../resources/img/javaone2013.jpg";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new ImageNextToText().ManipulatePdf(DEST);
        }
 
        private void ManipulatePdf(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
 
            Table table = new Table(UnitValue.CreatePercentArray(new float[] {1, 2}));
            table.AddCell(CreateImageCell(IMG1));
            table.AddCell(CreateTextCell(
                "This picture was taken at Java One.\nIt shows the iText crew at Java One in 2013."));
 
            doc.Add(table);
 
            doc.Close();
        }
 
        private static Cell CreateImageCell(string path)
        {
            Image img = new Image(ImageDataFactory.Create(path));
            img.SetWidth(UnitValue.CreatePercentValue(100));
            Cell cell = new Cell().Add(img);
            cell.SetBorder(Border.NO_BORDER);
            return cell;
        }
 
        private static Cell CreateTextCell(string text)
        {
            Cell cell = new Cell();
            Paragraph p = new Paragraph(text);
            p.SetTextAlignment(TextAlignment.RIGHT);
            cell.Add(p).SetVerticalAlignment(VerticalAlignment.BOTTOM);
            cell.SetBorder(Border.NO_BORDER);
            return cell;
        }
    }
}
ImagesInChunkInCell.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
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2019 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.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
 
namespace iText.Samples.Sandbox.Tables
{
    public class ImagesInChunkInCell
    {
        public static readonly string DEST = "../../results/sandbox/tables/images_in_chunk_in_cell.pdf";
 
        public static readonly string IMG = "../../resources/img/bulb.gif";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new ImagesInChunkInCell().ManipulatePdf(DEST);
        }
 
        private void ManipulatePdf(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
 
            Image image = new Image(ImageDataFactory.Create(IMG));
            Table table = new Table(new float[] {120});
            Paragraph listOfDots = new Paragraph();
 
            for (int i = 0; i < 40; i++)
            {
                listOfDots.Add(image);
                listOfDots.Add(new Text(" "));
            }
 
            table.AddCell(listOfDots);
 
            doc.Add(table);
 
            doc.Close();
        }
    }
}
ImagesNextToEachOther.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
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2019 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.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
 
namespace iText.Samples.Sandbox.Tables
{
    public class ImagesNextToEachOther
    {
        public static readonly string DEST = "../../results/sandbox/tables/image_next_to_each_other.pdf";
 
        public static readonly string IMG1 = "../../resources/img/javaone2013.jpg";
        public static readonly string IMG2 = "../../resources/img/berlin2013.jpg";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new ImagesNextToEachOther().ManipulatePdf(DEST);
        }
 
        private void ManipulatePdf(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
 
            Table table = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();
            table.AddCell(CreateImageCell(IMG1));
            table.AddCell(CreateImageCell(IMG2));
 
            doc.Add(table);
 
            doc.Close();
        }
 
        private static Cell CreateImageCell(string path)
        {
            Image img = new Image(ImageDataFactory.Create(path));
            return new Cell().Add(img.SetAutoScale(true).SetWidth(UnitValue.CreatePercentValue(100)));
        }
    }
}
MultipleImagesInCell.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
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2019 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.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
 
namespace iText.Samples.Sandbox.Tables
{
    public class MultipleImagesInCell
    {
        public static readonly string DEST = "../../results/sandbox/tables/multiple_images_in_cell.pdf";
 
        public static readonly string IMG1 = "../../resources/img/brasil.png";
 
        public static readonly string IMG2 = "../../resources/img/dog.bmp";
 
        public static readonly string IMG3 = "../../resources/img/fox.bmp";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new MultipleImagesInCell().ManipulatePdf(DEST);
        }
 
        private void ManipulatePdf(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
 
            Image img1 = new Image(ImageDataFactory.Create(IMG1));
            Image img2 = new Image(ImageDataFactory.Create(IMG2));
            Image img3 = new Image(ImageDataFactory.Create(IMG3));
 
            Table table = new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth();
            table.SetWidth(UnitValue.CreatePercentValue(50));
            table.AddCell("Different images, one after the other vertically:");
 
            Cell cell = new Cell();
 
            // There's no image autoscaling by default
            cell.Add(img1.SetAutoScale(true));
            cell.Add(img2.SetAutoScale(true));
            cell.Add(img3.SetAutoScale(true));
            table.AddCell(cell);
            doc.Add(table);
            doc.Add(new AreaBreak());
 
            // In the snippet after this autoscaling is not needed
            // Notice that we do not need to create new Image instances since the images had been already flushed
            img1.SetAutoScale(false);
            img2.SetAutoScale(false);
            img3.SetAutoScale(false);
            table = new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth();
            table.AddCell("Different images, one after the other vertically, but scaled:");
 
            cell = new Cell();
            img1.SetWidth(UnitValue.CreatePercentValue(20));
            cell.Add(img1);
            img2.SetWidth(UnitValue.CreatePercentValue(20));
            cell.Add(img2);
            img3.SetWidth(UnitValue.CreatePercentValue(20));
            cell.Add(img3);
            table.AddCell(cell);
 
            table.AddCell("Different images, one after the other horizontally:");
 
            // Notice that the table is not flushed yet so it's strictly forbidden to change image properties yet
            img1 = new Image(ImageDataFactory.Create(IMG1));
            img2 = new Image(ImageDataFactory.Create(IMG2));
            img3 = new Image(ImageDataFactory.Create(IMG3));
            Paragraph p = new Paragraph();
            img1.Scale(0.3f, 0.3f);
            p.Add(img1);
            p.Add(img2);
            p.Add(img3);
            table.AddCell(p);
            table.AddCell("Text and images (mixed):");
 
            img2 = new Image(ImageDataFactory.Create(IMG2));
            img3 = new Image(ImageDataFactory.Create(IMG3));
            p = new Paragraph("The quick brown ");
            p.Add(img3);
            p.Add(" jumps over the lazy ");
            p.Add(img2);
            cell = new Cell();
            cell.Add(p);
            table.AddCell(cell);
 
            doc.Add(table);
            
            doc.Close();
        }
    }
}
MultipleImagesInTable.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
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2019 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.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
 
namespace iText.Samples.Sandbox.Tables
{
    public class MultipleImagesInTable
    {
        public static readonly string DEST = "../../results/sandbox/tables/multiple_images_in_table.pdf";
 
        public static readonly string IMG1 = "../../resources/img/brasil.png";
 
        public static readonly string IMG2 = "../../resources/img/dog.bmp";
 
        public static readonly string IMG3 = "../../resources/img/fox.bmp";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new MultipleImagesInTable().ManipulatePdf(DEST);
        }
 
        private void ManipulatePdf(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
 
            Image img1 = new Image(ImageDataFactory.Create(IMG1));
            Image img2 = new Image(ImageDataFactory.Create(IMG2));
            Image img3 = new Image(ImageDataFactory.Create(IMG3));
 
            Table table = new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth();
            table.SetWidth(UnitValue.CreatePercentValue(20));
 
            img1.SetAutoScale(true);
            img2.SetAutoScale(true);
            img3.SetAutoScale(true);
 
            table.AddCell(img1);
            table.AddCell("Brazil");
            table.AddCell(img2);
            table.AddCell("Dog");
            table.AddCell(img3);
            table.AddCell("Fox");
 
            doc.Add(table);
 
            doc.Close();
        }
    }
}
PositionContentInCell.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
166
167
168
169
170
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2019 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.Image;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.Layout.Renderer;
 
namespace iText.Samples.Sandbox.Tables
{
    public class PositionContentInCell
    {
        public static readonly string DEST = "../../results/sandbox/tables/position_content_in_cell.pdf";
 
        public static readonly string IMG = "../../resources/img/info.png";
 
        private enum POSITION
        {
            TOP_LEFT,
            TOP_RIGHT,
            BOTTOM_LEFT,
            BOTTOM_RIGHT
        }
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new PositionContentInCell().ManipulatePdf(DEST);
        }
 
        private void ManipulatePdf(String dest)
        {
            // 1. Create a Document which contains a table:
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
            Table table = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();
            Cell cell1 = new Cell();
            Cell cell2 = new Cell();
            Cell cell3 = new Cell();
            Cell cell4 = new Cell();
 
            // 2. Inside that table, make each cell with specific height:
            cell1.SetHeight(50);
            cell2.SetHeight(50);
            cell3.SetHeight(50);
            cell4.SetHeight(50);
 
            // 3. Each cell has the same background image
            // 4. Add text in front of the image at specific position
            cell1.SetNextRenderer(new ImageAndPositionRenderer(cell1, new Image(ImageDataFactory.Create(IMG)), 
                "Top left", POSITION.TOP_LEFT));
            cell2.SetNextRenderer(new ImageAndPositionRenderer(cell2, new Image(ImageDataFactory.Create(IMG)),
                "Top right", POSITION.TOP_RIGHT));
            cell3.SetNextRenderer(new ImageAndPositionRenderer(cell3, new Image(ImageDataFactory.Create(IMG)),
                "Bottom left", POSITION.BOTTOM_LEFT));
            cell4.SetNextRenderer(new ImageAndPositionRenderer(cell4, new Image(ImageDataFactory.Create(IMG)),
                "Bottom right", POSITION.BOTTOM_RIGHT));
 
            // Wrap it all up!
            table.AddCell(cell1);
            table.AddCell(cell2);
            table.AddCell(cell3);
            table.AddCell(cell4);
 
            doc.Add(table);
 
            doc.Close();
        }
 
        private class ImageAndPositionRenderer : CellRenderer
        {
            private Image img;
            private String content;
            private POSITION position;
 
            public ImageAndPositionRenderer(Cell modelElement, Image img, String content, POSITION position)
                : base(modelElement)
            {
                this.img = img;
                this.content = content;
                this.position = position;
            }
 
            public override void Draw(DrawContext drawContext)
            {
                base.Draw(drawContext);
                
                Rectangle area = GetOccupiedAreaBBox();
                img.ScaleToFit(area.GetWidth(), area.GetHeight());
 
                drawContext.GetCanvas().AddXObject(img.GetXObject(),
                    area.GetX() + (area.GetWidth() - img.GetImageWidth() *
                                                    img.GetProperty<float>(Property.HORIZONTAL_SCALING)) / 2,
                    area.GetY() + (area.GetHeight() - img.GetImageHeight() *
                                                    img.GetProperty<float>(Property.VERTICAL_SCALING)) / 2,
                    img.GetImageWidth() * img.GetProperty<float>(Property.HORIZONTAL_SCALING));
 
                drawContext.GetCanvas().Stroke();
 
                Paragraph p = new Paragraph(content);
                Leading leading = p.GetDefaultProperty<Leading>(Property.LEADING);
 
                UnitValue defaultFontSizeUv = new DocumentRenderer(new Document(drawContext.GetDocument()))
                    .GetPropertyAsUnitValue(Property.FONT_SIZE);
 
                float defaultFontSize = defaultFontSizeUv.IsPointValue() ? defaultFontSizeUv.GetValue() : 12f;
                float x;
                float y;
                TextAlignment? alignment;
                switch (position)
                {
                    case POSITION.TOP_LEFT:
                    {
                        x = area.GetLeft() + 3;
                        y = area.GetTop() - defaultFontSize * leading.GetValue();
                        alignment = TextAlignment.LEFT;
                        break;
                    }
 
                    case POSITION.TOP_RIGHT:
                    {
                        x = area.GetRight() - 3;
                        y = area.GetTop() - defaultFontSize * leading.GetValue();
                        alignment = TextAlignment.RIGHT;
                        break;
                    }
 
                    case POSITION.BOTTOM_LEFT:
                    {
                        x = area.GetLeft() + 3;
                        y = area.GetBottom() + 3;
                        alignment = TextAlignment.LEFT;
                        break;
                    }
 
                    case POSITION.BOTTOM_RIGHT:
                    {
                        x = area.GetRight() - 3;
                        y = area.GetBottom() + 3;
                        alignment = TextAlignment.RIGHT;
                        break;
                    }
 
                    default:
                    {
                        x = 0;
                        y = 0;
                        alignment = TextAlignment.CENTER;
                        break;
                    }
                }
 
                new Canvas(drawContext.GetCanvas(), drawContext.GetDocument(), area).ShowTextAligned(p, x, y, alignment);
            }
        }
    }
}
PositionContentInCell2.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
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2019 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.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.Layout.Renderer;
 
namespace iText.Samples.Sandbox.Tables
{
    public class PositionContentInCell2
    {
        public static readonly string DEST = "../../results/sandbox/tables/position_content_in_cell2.pdf";
 
        public static readonly String IMG = "../../resources/img/info.png";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new PositionContentInCell2().ManipulatePdf(DEST);
        }
 
        private void ManipulatePdf(String dest)
        {
            // 1. Create a Document which contains a table:
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
            Table table = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();
            Cell cell1 = new Cell();
            Cell cell2 = new Cell();
            Cell cell3 = new Cell();
            Cell cell4 = new Cell();
            Cell cell5 = new Cell();
            Cell cell6 = new Cell();
            Cell cell7 = new Cell();
            Cell cell8 = new Cell();
 
            // 2. Inside that table, make each cell with specific height:
            cell1.SetHeight(50);
            cell2.SetHeight(50);
            cell3.SetHeight(50);
            cell4.SetHeight(50);
            cell5.SetHeight(50);
            cell6.SetHeight(50);
            cell7.SetHeight(50);
            cell8.SetHeight(50);
            
            Image img = new Image(ImageDataFactory.Create(IMG));
            
            // 3. Each cell has the same background image
            // 4. Add text in front of the image at specific position
            cell1.SetNextRenderer(new ImageAndPositionRenderer(cell1, 0, 1, img,
                "Top left", TextAlignment.LEFT));
            cell2.SetNextRenderer(new ImageAndPositionRenderer(cell2, 1, 1, img,
                "Top right", TextAlignment.RIGHT));
            cell3.SetNextRenderer(new ImageAndPositionRenderer(cell3, 0.5f, 1, img,
                "Top center", TextAlignment.CENTER));
            cell4.SetNextRenderer(new ImageAndPositionRenderer(cell4, 0.5f, 0, img,
                "Bottom center", TextAlignment.CENTER));
            cell5.SetNextRenderer(new ImageAndPositionRenderer(cell5, 0.5f, 0.5f,
                new Image(ImageDataFactory.Create(IMG)),
                "Middle center", TextAlignment.CENTER));
            cell6.SetNextRenderer(new ImageAndPositionRenderer(cell6, 0.5f, 0.5f,
                new Image(ImageDataFactory.Create(IMG)),
                "Middle center", TextAlignment.CENTER));
            cell7.SetNextRenderer(new ImageAndPositionRenderer(cell7, 0, 0, img,
                "Bottom left", TextAlignment.LEFT));
            cell8.SetNextRenderer(new ImageAndPositionRenderer(cell8, 1, 0, img,
                "Bottom right", TextAlignment.RIGHT));
 
            // Wrap it all up!
            table.AddCell(cell1);
            table.AddCell(cell2);
            table.AddCell(cell3);
            table.AddCell(cell4);
            table.AddCell(cell5);
            table.AddCell(cell6);
            table.AddCell(cell7);
            table.AddCell(cell8);
            doc.Add(table);
            
            doc.Close();
        }
 
        private class ImageAndPositionRenderer : CellRenderer
        {
            private Image img;
 
            private String content;
 
            private TextAlignment? alignment;
 
            private float wPct;
 
            private float hPct;
 
            public ImageAndPositionRenderer(Cell modelElement, float wPct, float hPct, Image img,
                String content, TextAlignment? alignment)
                : base(modelElement)
            {
                this.img = img;
                this.content = content;
                this.alignment = alignment;
                this.wPct = wPct;
                this.hPct = hPct;
            }
 
            public override void Draw(DrawContext drawContext)
            {
                base.Draw(drawContext);
                drawContext.GetCanvas().AddXObject(img.GetXObject(), GetOccupiedAreaBBox());
                drawContext.GetCanvas().Stroke();
 
                UnitValue fontSizeUv = GetPropertyAsUnitValue(Property.FONT_SIZE);
                float x = GetOccupiedAreaBBox().GetX() + wPct * GetOccupiedAreaBBox().GetWidth();
                float y = GetOccupiedAreaBBox().GetY() + hPct *
                          (GetOccupiedAreaBBox().GetHeight() - (fontSizeUv.IsPointValue()
                               ? fontSizeUv.GetValue()
                               : 12f) * 1.5f);
                new Document(drawContext.GetDocument()).ShowTextAligned(content, x, y, alignment);
            }
        }
    }
}
SimpleTable8.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
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2019 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.Kernel.Pdf;
using iText.Kernel.Pdf.Xobject;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
 
namespace iText.Samples.Sandbox.Tables
{
    public class SimpleTable8
    {
        public static readonly string DEST = "../../results/sandbox/tables/simple_table8.pdf";
 
        public static String SRC = "../../resources/pdfs/";
 
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
 
            new SimpleTable8().ManipulatePdf(DEST);
        }
 
        private void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
 
            Table table = new Table(UnitValue.CreatePercentArray(3)).UseAllAvailableWidth();
 
            PdfReader reader = new PdfReader(SRC + "header_test_file.pdf");
            PdfDocument srcDoc = new PdfDocument(reader);
            
            PdfFormXObject header = srcDoc.GetFirstPage().CopyAsFormXObject(pdfDoc);
 
            Cell cell = new Cell(1, 3).Add(new Image(header).SetWidth(UnitValue.CreatePercentValue(100))
                .SetAutoScale(true));
            table.AddCell(cell);
 
            for (int row = 1; row <= 50; row++)
            {
                for (int column = 1; column <= 3; column++)
                {
                    table.AddCell(String.Format("row {0}, column {1}", row, column));
                }
            }
 
            reader = new PdfReader(SRC + "footer_test_file.pdf");
            srcDoc = new PdfDocument(reader);
           
            PdfFormXObject footer = srcDoc.GetFirstPage().CopyAsFormXObject(pdfDoc);
 
            cell = new Cell(1, 3).Add(new Image(footer).SetWidth(UnitValue.CreatePercentValue(100))
                .SetAutoScale(true));
            table.AddCell(cell);
 
            doc.Add(table);
 
            doc.Close();
        }
    }
}

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


Tags
images tables

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