Table Example
iText is a free and open source library for creating and manipulating
PDF documents in Java. The following example shows inserting a table in PDF document.
package com.bethecoder.tutorials.itext.tests;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class Table {
/**
* @param args
* @throws DocumentException
* @throws IOException
* @throws MalformedURLException
*/
public static void main ( String [] args ) throws DocumentException, MalformedURLException, IOException {
Document document = new Document ( PageSize.A4 ) ;
PdfWriter.getInstance ( document, new FileOutputStream ( "test11.pdf" )) ;
//Open the document before adding any content
document.open () ;
//Create a table with 3 columns
PdfPTable pdfPTable = new PdfPTable ( 3 ) ;
//Add Header
pdfPTable.addCell ( "S. No." ) ;
pdfPTable.addCell ( "Author Name" ) ;
pdfPTable.addCell ( "Photo" ) ;
//Add first row
pdfPTable.addCell ( "1" ) ;
pdfPTable.addCell ( "Sriram Kasireddi" ) ;
pdfPTable.addCell ( Image.getInstance ( "C:\\baby.jpg" )) ;
//Add second row
pdfPTable.addCell ( "2" ) ;
pdfPTable.addCell ( "Sudhakar Kasireddi" ) ;
pdfPTable.addCell ( Image.getInstance ( "C:\\baby.jpg" )) ;
//Add table to document
document.add ( pdfPTable ) ;
//Close the document
document.close () ;
}
}
It gives the following output,