Skip to content

Instantly share code, notes, and snippets.

@migueldoctor
Created November 7, 2022 12:44
Show Gist options
  • Save migueldoctor/4b1320cffcc2efb4ec1cb59bba8cb529 to your computer and use it in GitHub Desktop.
Save migueldoctor/4b1320cffcc2efb4ec1cb59bba8cb529 to your computer and use it in GitHub Desktop.
Sample 5 Java PDF generation with Tables
package com.kesizo.java.pdf.sample;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;
public class Main {
public static void main(String[] args) {
Document myPDFDoc = new Document(PageSize.A4,
40f, // left
40f, // right
200f, // top
150f); // down
Rectangle footer = new Rectangle(30f, 30f, PageSize.A4.getRight(30f), 140f);
footer.setBorder(Rectangle.BOX);
footer.setBorderColor(Color.BLACK);
footer.setBorderWidth(2f);
Rectangle header = new Rectangle(30f, 30f, PageSize.A4.getRight(30f), 140f);
header.setBorder(Rectangle.BOX);
header.setBorderColor(Color.BLUE);
header.setBorderWidth(1f);
header.setTop(PageSize.A4.getTop(30f));
header.setBottom(PageSize.A4.getTop(180f));
// Define a string as title
String title = "Learning OpenPDF with Java";
// Define a paragraph
String lorenIpsum1 = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo"+
" ligula eget dolor. Aenean massa.Cum sociis natoque penatibus et magnis dis" +
" parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec," +
" pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim"+
" Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu."+
" In enim justo, rhoncus ut, imperdiet a, venenatis vitae,"+
" justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt."+
" Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.";
//1) Let's create a Table object
Table myTable = new Table(3); // 3 columns
myTable.setPadding(2f);
myTable.setSpacing(1f);
myTable.setWidth(100f);
//2) Create the header of the table
ArrayList<String> headerTable = new ArrayList<>();
headerTable.add("Name");
headerTable.add("Surname");
headerTable.add("Age");
headerTable.forEach(e -> {
Cell current = new Cell(new Phrase(e));
current.setHeader(true);
current.setBackgroundColor(Color.LIGHT_GRAY);
myTable.addCell(current);
});
// 3) Then create a list of rows and add them to the table
LinkedHashMap<Integer, List<String>> listRows = new LinkedHashMap<>();
listRows.put(1, Arrays.asList("Miguel","Surname", "37"));
listRows.put(2, Arrays.asList("Username1","Surname2", "40"));
listRows.forEach((index,userDetailRow) -> {
String currentName = userDetailRow.get(0);
String currentSurname = userDetailRow.get(1);
String currentAge = userDetailRow.get(2);
myTable.addCell(new Cell(new Phrase(currentName)));
myTable.addCell(new Cell(new Phrase(currentSurname)));
myTable.addCell(new Cell(new Phrase(currentAge)));
});
try {
FileOutputStream pdfOutputFile = new FileOutputStream("./sample1.pdf");
final PdfWriter pdfWriter = PdfWriter.getInstance(myPDFDoc, pdfOutputFile);
pdfWriter.setPageEvent(new PdfPageEventHelper() {
@Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
cb.rectangle(header);
cb.rectangle(footer);
}
});
myPDFDoc.open(); // Open the Document
/* Here we add some metadata to the generated pdf */
myPDFDoc.addTitle("This is a simple PDF example");
myPDFDoc.addSubject("This is a tutorial explaining how to use openPDF");
myPDFDoc.addKeywords("Java, OpenPDF, Basic sample");
myPDFDoc.addCreator("Miguel and Kesizo.com");
myPDFDoc.addAuthor("Miguel Doctor");
/* End of the adding metadata section */
// Create a Font object
Font titleFont = new Font(Font.COURIER, 20f, Font.BOLDITALIC, Color.BLUE);
// Create a paragraph with the new font
Paragraph paragraph = new Paragraph(title,titleFont);
// Element class provides properties to align
// Content elements within the document
paragraph.setAlignment(Element.ALIGN_CENTER);
myPDFDoc.add(paragraph);
// Adding an empty line
myPDFDoc.add(new Paragraph(Chunk.NEWLINE));
// Include the text as content of the pdf
myPDFDoc.add(new Paragraph(lorenIpsum1));
// 4)Finally add the table to the document
myPDFDoc.add(myTable);
myPDFDoc.close();
pdfWriter.close();
} catch (IOException de) {
System.err.println(de.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment