The Table is used to add the table in the pdf file. We have to define the number of columns in the PdfTable constructor. It is represented by com.itextpdf.text.PdfPTable class.
Steps:
1. Create Document instance. It represents the current document to which we are adding content.
2. Create OutputStream instance. It represents the generated pdf.
3. Create PDFWriter instance and pass Document and OutputStream instance to its constructor.
4. Open the Document by calling document.open().
5. Add the content to the document by calling document.add() method using Table object.
6. Close the document by calling document.close() method.
Example:
PDFTableExample.java
import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; /** * This class is used to create a pdf file using iText jar. * @author w3schools */ public class PDFTableExample { public static void main(String args[]){ try { //Create Document instance. Document document = new Document(); //Create OutputStream instance. OutputStream outputStream = new FileOutputStream(new File("D:\\TestTableFile.pdf")); //Create PDFWriter instance. PdfWriter.getInstance(document, outputStream); //Open the document. document.open(); //Create Table object, Here 4 specify the no. of columns PdfPTable pdfPTable = new PdfPTable(4); //Create cells PdfPCell pdfPCell1 = new PdfPCell(new Paragraph("Cell 1")); PdfPCell pdfPCell2 = new PdfPCell(new Paragraph("Cell 2")); PdfPCell pdfPCell3 = new PdfPCell(new Paragraph("Cell 3")); PdfPCell pdfPCell4 = new PdfPCell(new Paragraph("Cell 4")); //Add cells to table pdfPTable.addCell(pdfPCell1); pdfPTable.addCell(pdfPCell2); pdfPTable.addCell(pdfPCell3); pdfPTable.addCell(pdfPCell4); //Add content to the document using Table objects. document.add(pdfPTable); //Close document and outputStream. document.close(); outputStream.close(); System.out.println("Pdf created successfully."); } catch (Exception e) { e.printStackTrace(); } } } |
Output:
Pdf created successfully. |
Download this example.
Next Topic: Java iText image.
Previous Topic: Java iText list.