Adding images to a table

31st May 2016
admin-marketing
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
89
90
91
92
93
94
/*
    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 com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import org.junit.experimental.categories.Category;
 
import java.io.File;
 
@Category(SampleTest.class)
public class AddOverlappingImage extends GenericTest {
    public static final String DEST = "./target/test/resources/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);
    }
 
    @Override
    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
48
49
50
51
52
53
/*
    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 com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import org.junit.experimental.categories.Category;
 
import java.io.File;
 
@Category(SampleTest.class)
public class IconDescriptionTable extends GenericTest {
    public static final String DEST = "./target/test/resources/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);
    }
 
    @Override
    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
69
70
71
72
73
74
/*
    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 com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import org.junit.experimental.categories.Category;
 
import java.io.File;
import java.net.MalformedURLException;
 
@Category(SampleTest.class)
public class ImageNextToText extends GenericTest {
    public static final String DEST = "./target/test/resources/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;
    }
 
    @Override
    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
51
52
53
54
55
56
/*
    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 com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import org.junit.experimental.categories.Category;
 
import java.io.File;
 
@Category(SampleTest.class)
public class ImagesInChunkInCell extends GenericTest {
    public static final String DEST = "./target/test/resources/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);
    }
 
    @Override
    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
55
56
57
58
59
60
/*
    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 com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import org.junit.experimental.categories.Category;
 
import java.io.File;
import java.net.MalformedURLException;
 
@Category(SampleTest.class)
public class ImagesNextToEachOther extends GenericTest {
    public static final String DEST = "./target/test/resources/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)));
    }
 
    @Override
    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
113
114
115
116
117
118
/*
    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 com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import java.io.File;
 
import org.junit.experimental.categories.Category;
 
@Category(SampleTest.class)
public class MultipleImagesInCell extends GenericTest {
    public static final String DEST
            = "./target/test/resources/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);
    }
 
    @Override
    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
68
69
70
71
72
73
/*
    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 com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import java.io.File;
 
import org.junit.experimental.categories.Category;
 
@Category(SampleTest.class)
public class MultipleImagesInTable extends GenericTest {
    public static final String DEST
            = "./target/test/resources/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);
    }
 
    @Override
    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
146
147
148
149
150
151
/*
    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 com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import org.junit.experimental.categories.Category;
 
import java.io.File;
 
@Category(SampleTest.class)
public class PositionContentInCell extends GenericTest {
    public static final String DEST = "./target/test/resources/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);
    }
 
    @Override
    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
127
128
129
130
131
132
/*
    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 com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import org.junit.experimental.categories.Category;
 
import java.io.File;
 
@Category(SampleTest.class)
public class PositionContentInCell2 extends GenericTest {
    public static final String DEST = "./target/test/resources/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);
    }
 
    @Override
    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
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 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 com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
 
import org.junit.experimental.categories.Category;
 
import java.io.File;
 
@Category(SampleTest.class)
public class SimpleTable8 extends GenericTest {
    public static final String DEST = "./target/test/resources/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);
    }
 
    @Override
    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();
    }
}

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