Skip to content

Instantly share code, notes, and snippets.

@documentprocessing
Created June 2, 2025 16:11
Show Gist options
  • Select an option

  • Save documentprocessing/e1dab8e02022bfb1f313b36dec79f733 to your computer and use it in GitHub Desktop.

Select an option

Save documentprocessing/e1dab8e02022bfb1f313b36dec79f733 to your computer and use it in GitHub Desktop.
Add a Table to a PDF with OpenPDF Java API
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class PdfTableExample {
public static void main(String[] args) {
// Step 1: Create Document and PdfWriter
Document document = new Document();
try {
PdfWriter.getInstance(
document,
new FileOutputStream("pdf-with-table.pdf")
);
document.open();
// Step 2: Add title
Font titleFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16);
document.add(new Paragraph("Monthly Sales Report", titleFont));
document.add(new Paragraph("\n")); // Add spacing
// Step 3: Create a table with 4 columns
PdfPTable table = new PdfPTable(4);
table.setWidthPercentage(100); // Table width = 100% of page
// Step 4: Define table headers
Font headerFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12);
table.addCell(new Paragraph("Product", headerFont));
table.addCell(new Paragraph("Qty", headerFont));
table.addCell(new Paragraph("Price", headerFont));
table.addCell(new Paragraph("Total", headerFont));
// Step 5: Add sample data rows
Font bodyFont = FontFactory.getFont(FontFactory.HELVETICA, 10);
String[][] data = {
{"Laptop", "5", "$1200", "$6000"},
{"Mouse", "20", "$25", "$500"},
{"Keyboard", "15", "$45", "$675"}
};
for (String[] row : data) {
for (String cell : row) {
table.addCell(new Paragraph(cell, bodyFont));
}
}
// Step 6: Add table to document
document.add(table);
document.close();
System.out.println("PDF with table created successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment