DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

How to add PDF table in Java

In this article I am going to introduce how to add table to PDF file in Java applications by Free Spire.PDF for Java. Spire.PDF for java offers PdfTable and PdfGrid class to draw table to PDF.

How to create table by PDFTable class and formatting the table.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.tables.*;
import java.awt.*;
import java.awt.geom.Point2D;

public class PDFTable {
    public static void main(String[] args) throws Exception {
        //Create a PDF document
        PdfDocument doc = new PdfDocument();
        //set margin
        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
        PdfMargins margin = new PdfMargins();
        margin.setTop(unitCvtr.convertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point));
        margin.setBottom(margin.getTop());
        margin.setLeft(unitCvtr.convertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point));
        margin.setRight(margin.getLeft());

        //Create one page
        PdfPageBase page = doc.getPages().add(PdfPageSize.A4, margin);

        //Add a table
        PdfTable table = new PdfTable();
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));
        table.getStyle().setBorderPen(new PdfPen(brush, 0.5f));
        table.getStyle().getHeaderStyle().setStringFormat(new PdfStringFormat(PdfTextAlignment.Center));
        table.getStyle().setHeaderSource(PdfHeaderSource.Rows);
        table.getStyle().setHeaderRowCount(1);
        table.getStyle().setShowHeader(true);
        table.getStyle().setCellPadding(2);
        table.getStyle().setHeaderSource(PdfHeaderSource.Rows);
        table.getStyle().setHeaderRowCount(1);
        table.getStyle().setShowHeader(true);

        //Set the title and style
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial",Font.PLAIN, 12));
        table.getStyle().getHeaderStyle().setFont(font);
        table.getStyle().getHeaderStyle().setBackgroundBrush(PdfBrushes.getCadetBlue());
        PdfTrueTypeFont fontBody = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,10));
        //Set the font for the odd lines
        table.getStyle().getDefaultStyle().setFont(fontBody);
        //Set the font for the even lines
        table.getStyle().getAlternateStyle().setFont(fontBody);

        //Define the data
        String[] data = {
                "Name;Capital;Continent;Area;Population",
                "Argentina;Buenos Aires;South America;2777815;32300003",
                "Brazil;Brasilia;South America;8511196;150400000",
                "Canada;Ottawa;North America;9976147;26500000",
                "Ecuador;Quito;South America;455502;10600000",
                "Guyana;Georgetown;South America;214969;800000",
                "Mexico;Mexico City;North America;1967180;88600000",
                "Paraguay;Asuncion;South America;406576;4660000",
                "United States of America;Washington;North America;9363130;249200000",
                "Uruguay;Montevideo;South America;176140;3002000",
        };
        String[][] dataSource = new String[data.length][];
        for (int i = 0; i < data.length; i++) {
            dataSource[i] = data[i].split("[;]", -1);
        }

        table.setDataSource(dataSource);
        for(int i = 0; i < table.getColumns().getCount();i++)
        {
            PdfColumn column= table.getColumns().get(i);
            column.setStringFormat(new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));
        }

        //Add the table
        table.draw(page, new Point2D.Float(0, 50));

        //Save the document to file
        doc.saveToFile("output/addTable.pdf", FileFormat.PDF);
    }
}
Enter fullscreen mode Exit fullscreen mode

Effective screenshot after adding table to PDF:
Add PDF Table

Add PDF grid and formatting the table

The following code will demonstrate how to use the PdfGrid class to create a table, merge cells, set cell background, set font and other formatting operations.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.grid.PdfGrid;
import java.awt.*;


public class PDFGrid {
    public static void main(String[] args) throws Exception {
        //Create a PDF document
        PdfDocument doc = new PdfDocument();

        //set margin
        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
        PdfMargins margin = new PdfMargins();
        margin.setTop(unitCvtr.convertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point));
        margin.setBottom(margin.getTop());
        margin.setLeft(unitCvtr.convertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point));
        margin.setRight(margin.getLeft());

        //Create one page
        PdfPageBase page = doc.getPages().add(PdfPageSize.A4, margin);

        //Add a table
        PdfGrid grid = new PdfGrid();
        grid.getStyle().setCellPadding(new PdfPaddings(1, 1, 1, 1));

        //set the cell padding, font, text brush, background brush of the grid
        grid.getStyle().setCellPadding(new PdfPaddings(3,3,3,3));
        grid.getStyle().setFont(new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,10), true));
        grid.getStyle().setTextBrush(PdfBrushes.getBlack());
        grid.getStyle().setBackgroundBrush(PdfBrushes.getLightGray());

        //create a PdfBorders object
        PdfBorders borders= new PdfBorders();
        borders.setAll(new PdfPen(PdfBrushes.getWhite(),1f));

        //Define the data
        String[] data = {
                "Continent;Name;Capital;Area;Population",
                "South America;Argentina;Buenos Aires;2777815;32300003",
                "South America;Brazil;Brasilia;8511196;150400000",
                "North America;Canada;Ottawa;9976147;26500000",
                "North America;Mexico;Mexico City;1967180;88600000",
                "South America;Ecuador;Quito;455502;10600000",
                "South America;Guyana;Georgetown;214969;800000",
                "South America;Paraguay;Asuncion;406576;4660000",
                "South America;Uruguay;Montevideo;176140;3002000",
        String[][] dataSource = new String[data.length][];
        for (int i = 0; i < data.length; i++) {
            dataSource[i] = data[i].split("[;]", -1);
        }

        //fill the grid with data
        grid.setDataSource(dataSource);

        //set the width of the last column
        grid.getColumns().get(grid.getColumns().getCount()-1).setWidth(60f);

        //vertically span cells
        grid.getRows().get(1).getCells().get(0).setRowSpan(2);
        grid.getRows().get(3).getCells().get(0).setRowSpan(2);
        grid.getRows().get(5).getCells().get(0).setRowSpan(2);
        grid.getRows().get(7).getCells().get(0).setRowSpan(2);

        for (int i = 0; i < data.length ; i++) {

            //set the height of each row
            grid.getRows().get(i).setHeight(30f);
            //set the background color of the first column
            grid.getRows().get(i).getCells().get(0).getStyle().setBackgroundBrush(PdfBrushes.getDarkGray());
            //set the font of the first column
            grid.getRows().get(i).getCells().get(0).getStyle().setFont(new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,12),true));

            for (int j = 0; j < grid.getColumns().getCount(); j++) {

                //apply border style to all cells
                grid.getRows().get(i).getCells().get(j).getStyle().setBorders(borders);
                //apply text alignment to all cells
                grid.getRows().get(i).getCells().get(j).setStringFormat(new PdfStringFormat(PdfTextAlignment.Center,PdfVerticalAlignment.Middle));
                //set the font of the first row
                grid.getRows().get(0).getCells().get(j).getStyle().setFont(new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,12),true));
                //set the background color of the first row
                grid.getRows().get(0).getCells().get(j).getStyle().setBackgroundBrush(PdfBrushes.getDarkGray());

            }
        }

        //Add the table
        grid.draw(page,0,30);

        //Save the document to file
        doc.saveToFile("output/addGrid.pdf", FileFormat.PDF);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
Add PDF Grid

Top comments (0)