Skip to main content
Skip table of contents

Adding a background to a table

Examples written in answer to questions such as:

coloredbackground

JAVA
JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.tables;

import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
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.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;

import java.io.File;

public class ColoredBackground {
    public static final String DEST = "./target/sandbox/tables/colored_background.pdf";

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

        new ColoredBackground().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);

        PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
        Table table = new Table(UnitValue.createPercentArray(16)).useAllAvailableWidth();

        for (int aw = 0; aw < 16; aw++) {
            Cell cell = new Cell().add(new Paragraph("hi")
                    .setFont(font)
                    .setFontColor(ColorConstants.WHITE));
            cell.setBackgroundColor(ColorConstants.BLUE);
            cell.setBorder(Border.NO_BORDER);
            cell.setTextAlignment(TextAlignment.CENTER);
            table.addCell(cell);
        }

        doc.add(table);

        doc.close();
    }
}


C#
C#
using System;
using System.IO;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Font;
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 ColoredBackground
    {
        public static readonly string DEST = "results/sandbox/tables/colored_background.pdf";

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

            new ColoredBackground().ManipulatePdf(DEST);
        }

        private void ManipulatePdf(string dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
            
            PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
            Table table = new Table(UnitValue.CreatePercentArray(16)).UseAllAvailableWidth();
            
            for (int aw = 0; aw < 16; aw++)
            {
                Cell cell = new Cell().Add(new Paragraph("hi")
                    .SetFont(font)
                    .SetFontColor(ColorConstants.WHITE));
                cell.SetBackgroundColor(ColorConstants.BLUE);
                cell.SetBorder(Border.NO_BORDER);
                cell.SetTextAlignment(TextAlignment.CENTER);
                table.AddCell(cell);
            }

            doc.Add(table);

            doc.Close();
        }
    }
}


imagebackground

JAVA
JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.tables;

import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.DeviceGray;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
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.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DrawContext;
import com.itextpdf.layout.renderer.IRenderer;

import java.io.File;

public class ImageBackground {
    public static final String DEST = "./target/sandbox/tables/image_background.pdf";

    public static final String IMG = "./src/main/resources/img/bruno.jpg";

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

        new ImageBackground().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(1));
        table.setWidth(400);

        Cell cell = new Cell();
        PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA);
        Paragraph p = new Paragraph("A cell with an image as background color.")
                .setFont(font).setFontColor(DeviceGray.WHITE);
        cell.add(p);

        Image img = new Image(ImageDataFactory.create(IMG));

        // Draws an image as the cell's background
        cell.setNextRenderer(new ImageBackgroundCellRenderer(cell, img));
        cell.setHeight(600 * img.getImageHeight() / img.getImageWidth());
        table.addCell(cell);

        doc.add(table);

        doc.close();
    }


    private static class ImageBackgroundCellRenderer extends CellRenderer {
        protected Image img;

        public ImageBackgroundCellRenderer(Cell modelElement, Image img) {
            super(modelElement);
            this.img = img;
        }

        // If a renderer overflows on the next area, iText uses #getNextRenderer() method to create a new renderer for the overflow part.
        // If #getNextRenderer() isn't overridden, the default method will be used and thus the default rather than the custom
        // renderer will be created
        @Override
        public IRenderer getNextRenderer() {
            return new ImageBackgroundCellRenderer((Cell) modelElement, img);
        }

        @Override
        public void draw(DrawContext drawContext) {
            img.scaleToFit(getOccupiedAreaBBox().getWidth(), getOccupiedAreaBBox().getHeight());
            drawContext.getCanvas().addXObjectFittedIntoRectangle(img.getXObject(), getOccupiedAreaBBox());
            super.draw(drawContext);
        }
    }
}


C#
C#
using System;
using System.IO;
using iText.IO.Font.Constants;
using iText.IO.Image;
using iText.Kernel.Colors;
using iText.Kernel.Font;
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 ImageBackground
    {
        public static readonly string DEST = "results/sandbox/tables/image_background.pdf";

        public static readonly string IMG = "../../../resources/img/bruno.jpg";

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

            new ImageBackground().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(1));
            table.SetWidth(400);

            Cell cell = new Cell();
            PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
            Paragraph p = new Paragraph("A cell with an image as background color.")
                .SetFont(font).SetFontColor(DeviceGray.WHITE);
            cell.Add(p);

            Image img = new Image(ImageDataFactory.Create(IMG));

            // Draws an image as the cell's background
            cell.SetNextRenderer(new ImageBackgroundCellRenderer(cell, img));
            cell.SetHeight(600 * img.GetImageHeight() / img.GetImageWidth());
            table.AddCell(cell);

            doc.Add(table);

            doc.Close();
        }

        private class ImageBackgroundCellRenderer : CellRenderer
        {
            private Image img;

            public ImageBackgroundCellRenderer(Cell modelElement, Image img)
                : base(modelElement)
            {
                this.img = img;
            }            
            
            // If renderer overflows on the next area, iText uses getNextRender() method to create a renderer for the overflow part.
            // If getNextRenderer isn't overriden, the default method will be used and thus a default rather than custom
            // renderer will be created
            public override IRenderer GetNextRenderer()
            {
                return new ImageBackgroundCellRenderer((Cell) modelElement, img);
            }

            public override void Draw(DrawContext drawContext)
            {
                img.ScaleToFit(GetOccupiedAreaBBox().GetWidth(), GetOccupiedAreaBBox().GetHeight());
                drawContext.GetCanvas().AddXObjectFittedIntoRectangle(img.GetXObject(), GetOccupiedAreaBBox());
                base.Draw(drawContext);
            }
        }
    }
}



simpletable10

JAVA
JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.tables;

import com.itextpdf.kernel.colors.ColorConstants;
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.properties.UnitValue;

import java.io.File;

public class SimpleTable10 {
    public static final String DEST = "./target/sandbox/tables/simple_table10.pdf";

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

        new SimpleTable10().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();

        Cell sn = new Cell(2, 1).add(new Paragraph("S/N"));
        sn.setBackgroundColor(ColorConstants.YELLOW);
        table.addCell(sn);

        Cell name = new Cell(1, 3).add(new Paragraph("Name"));
        name.setBackgroundColor(ColorConstants.CYAN);
        table.addCell(name);

        Cell age = new Cell(2, 1).add(new Paragraph("Age"));
        age.setBackgroundColor(ColorConstants.GRAY);
        table.addCell(age);

        Cell surname = new Cell().add(new Paragraph("SURNAME"));
        surname.setBackgroundColor(ColorConstants.BLUE);
        table.addCell(surname);

        Cell firstname = new Cell().add(new Paragraph("FIRST NAME"));
        firstname.setBackgroundColor(ColorConstants.RED);
        table.addCell(firstname);

        Cell middlename = new Cell().add(new Paragraph("MIDDLE NAME"));
        middlename.setBackgroundColor(ColorConstants.GREEN);
        table.addCell(middlename);

        Cell f1 = new Cell().add(new Paragraph("1"));
        f1.setBackgroundColor(ColorConstants.PINK);
        table.addCell(f1);

        Cell f2 = new Cell().add(new Paragraph("James"));
        f2.setBackgroundColor(ColorConstants.MAGENTA);
        table.addCell(f2);

        Cell f3 = new Cell().add(new Paragraph("Fish"));
        f3.setBackgroundColor(ColorConstants.ORANGE);
        table.addCell(f3);

        Cell f4 = new Cell().add(new Paragraph("Stone"));
        f4.setBackgroundColor(ColorConstants.DARK_GRAY);
        table.addCell(f4);

        Cell f5 = new Cell().add(new Paragraph("17"));
        f5.setBackgroundColor(ColorConstants.LIGHT_GRAY);
        table.addCell(f5);

        doc.add(table);

        doc.close();
    }
}


C#
C#
using System;
using System.IO;
using iText.Kernel.Colors;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;

namespace iText.Samples.Sandbox.Tables
{
    public class SimpleTable10
    {
        public static readonly string DEST = "results/sandbox/tables/simple_table10.pdf";

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

            new SimpleTable10().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(5)).UseAllAvailableWidth();

            Cell sn = new Cell(2, 1).Add(new Paragraph("S/N"));
            sn.SetBackgroundColor(ColorConstants.YELLOW);
            table.AddCell(sn);

            Cell name = new Cell(1, 3).Add(new Paragraph("Name"));
            name.SetBackgroundColor(ColorConstants.CYAN);
            table.AddCell(name);

            Cell age = new Cell(2, 1).Add(new Paragraph("Age"));
            age.SetBackgroundColor(ColorConstants.GRAY);
            table.AddCell(age);

            Cell surname = new Cell().Add(new Paragraph("SURNAME"));
            surname.SetBackgroundColor(ColorConstants.BLUE);
            table.AddCell(surname);

            Cell firstname = new Cell().Add(new Paragraph("FIRST NAME"));
            firstname.SetBackgroundColor(ColorConstants.RED);
            table.AddCell(firstname);

            Cell middlename = new Cell().Add(new Paragraph("MIDDLE NAME"));
            middlename.SetBackgroundColor(ColorConstants.GREEN);
            table.AddCell(middlename);

            Cell f1 = new Cell().Add(new Paragraph("1"));
            f1.SetBackgroundColor(ColorConstants.PINK);
            table.AddCell(f1);

            Cell f2 = new Cell().Add(new Paragraph("James"));
            f2.SetBackgroundColor(ColorConstants.MAGENTA);
            table.AddCell(f2);

            Cell f3 = new Cell().Add(new Paragraph("Fish"));
            f3.SetBackgroundColor(ColorConstants.ORANGE);
            table.AddCell(f3);

            Cell f4 = new Cell().Add(new Paragraph("Stone"));
            f4.SetBackgroundColor(ColorConstants.DARK_GRAY);
            table.AddCell(f4);

            Cell f5 = new Cell().Add(new Paragraph("17"));
            f5.SetBackgroundColor(ColorConstants.LIGHT_GRAY);
            table.AddCell(f5);

            doc.Add(table);

            doc.Close();
        }
    }
}



tiledbackground

JAVA
JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.tables;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.colors.PatternColor;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.canvas.PdfPatternCanvas;
import com.itextpdf.kernel.pdf.colorspace.PdfPattern;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.BoxSizingPropertyValue;
import com.itextpdf.layout.properties.Property;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DrawContext;
import com.itextpdf.layout.renderer.IRenderer;

import java.io.File;

public class TiledBackground {
    public static final String DEST = "./target/sandbox/tables/tiled_background.pdf";

    public static final String IMG1 = "./src/main/resources/img/ALxRF.png";

    public static final String IMG2 = "./src/main/resources/img/bulb.gif";

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

        new TiledBackground().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(2)).useAllAvailableWidth();

        Cell cell = new Cell();
        ImageData image = ImageDataFactory.create(IMG1);
        cell.setNextRenderer(new TiledImageBackgroundCellRenderer(cell, image));
        cell.setProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX);
        cell.setHeight(770).setBorder(Border.NO_BORDER);
        table.addCell(cell);

        cell = new Cell();
        image = ImageDataFactory.create(IMG2);
        cell.setNextRenderer(new TiledImageBackgroundCellRenderer(cell, image));
        cell.setProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX);
        cell.setHeight(770).setBorder(Border.NO_BORDER);
        table.addCell(cell);

        doc.add(table);

        doc.close();
    }


    private static class TiledImageBackgroundCellRenderer extends CellRenderer {
        protected ImageData img;

        public TiledImageBackgroundCellRenderer(Cell modelElement, ImageData img) {
            super(modelElement);
            this.img = img;
        }

        // If a renderer overflows on the next area, iText uses #getNextRenderer() method to create a new renderer for the overflow part.
        // If #getNextRenderer() isn't overridden, the default method will be used and thus the default rather than the custom
        // renderer will be created
        @Override
        public IRenderer getNextRenderer() {
            return new TiledImageBackgroundCellRenderer((Cell) modelElement, img);
        }

        @Override
        public void draw(DrawContext drawContext) {
            PdfPattern.Tiling imgPattern = new PdfPattern.Tiling(img.getWidth(), img.getHeight(), img.getWidth(),
                    img.getHeight());

            PdfPatternCanvas patternCanvas = new PdfPatternCanvas(imgPattern, drawContext.getDocument());
            patternCanvas.addImageAt(img, 0, 0, false);

            PdfCanvas canvas = drawContext.getCanvas();

            canvas.saveState();

            colorRectangle(canvas, new PatternColor(imgPattern), getOccupiedAreaBBox().getX(),
                    getOccupiedAreaBBox().getY(), getOccupiedAreaBBox().getWidth(), getOccupiedAreaBBox().getHeight());

            canvas.setFillColor(new PatternColor(imgPattern));
            canvas.stroke();

            canvas.restoreState();
        }

        private static void colorRectangle(PdfCanvas canvas, Color color, float x, float y, float width, float height) {
            canvas
                    .saveState()
                    .setFillColor(color)
                    .rectangle(x, y, width, height)
                    .fillStroke()
                    .restoreState();
        }
    }
}


C#
C#
using System;
using System.IO;
using iText.IO.Image;
using iText.Kernel.Colors;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Colorspace;
using iText.Layout;
using iText.Layout.Borders;
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.Layout.Renderer;

namespace iText.Samples.Sandbox.Tables
{
    public class TiledBackground
    {
        public static readonly string DEST = "results/sandbox/tables/tiled_background.pdf";

        public static readonly String IMG1 = "../../../resources/img/ALxRF.png";

        public static readonly String IMG2 = "../../../resources/img/bulb.gif";

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

            new TiledBackground().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();

            Cell cell = new Cell();
            ImageData image = ImageDataFactory.Create(IMG1);
            cell.SetNextRenderer(new TiledImageBackgroundCellRenderer(cell, image));
            cell.SetProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX);
            cell.SetHeight(770).SetBorder(Border.NO_BORDER);
            table.AddCell(cell);

            cell = new Cell();
            image = ImageDataFactory.Create(IMG2);
            cell.SetNextRenderer(new TiledImageBackgroundCellRenderer(cell, image));
            cell.SetProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX);
            cell.SetHeight(770).SetBorder(Border.NO_BORDER);
            table.AddCell(cell);

            doc.Add(table);

            doc.Close();
        }

        private class TiledImageBackgroundCellRenderer : CellRenderer
        {
            private ImageData img;

            public TiledImageBackgroundCellRenderer(Cell modelElement, ImageData img)
                : base(modelElement)
            {
                this.img = img;
            }

            // If renderer overflows on the next area, iText uses getNextRender() method to create a renderer for the overflow part.
            // If getNextRenderer isn't overriden, the default method will be used and thus a default rather than custom
            // renderer will be created
            public override IRenderer GetNextRenderer()
            {
                return new TiledImageBackgroundCellRenderer((Cell) modelElement, img);
            }

            public override void Draw(DrawContext drawContext)
            {
                PdfPattern.Tiling imgPattern = new PdfPattern.Tiling(img.GetWidth(), img.GetHeight(),
                    img.GetWidth(), img.GetHeight());

                PdfPatternCanvas patternCanvas = new PdfPatternCanvas(imgPattern, drawContext.GetDocument());
                patternCanvas.AddImageAt(img, 0, 0, false);
                
                PdfCanvas canvas = drawContext.GetCanvas();
                
                canvas.SaveState();

                ColorRectangle(canvas, new PatternColor(imgPattern), GetOccupiedAreaBBox().GetX(),
                    GetOccupiedAreaBBox().GetY(), GetOccupiedAreaBBox().GetWidth(), GetOccupiedAreaBBox().GetHeight());

                canvas.SetFillColor(new PatternColor(imgPattern));
                canvas.Stroke();

                canvas.RestoreState();
            }

            private static void ColorRectangle(PdfCanvas canvas, Color color, float x, float y, float width, float height) {
                canvas
                    .SaveState()
                    .SetFillColor(color)
                    .Rectangle(x, y, width, height)
                    .FillStroke()
                    .RestoreState();
            }
        }
    }
}


Resources

ALxRF.png
bruno.jpg
bulb.gif

Results

cmp_colored_background.pdf

cmp_image_background.pdf

cmp_simple_table10.pdf

cmp_tiled_background.pdf

JavaScript errors detected

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

If this problem persists, please contact our support.