How to put database records into an iText pdf table report in Java

997 Views Asked by At

So I want to connect my records into an iText table report. I managed to just list all my records inside the PDF but not putting them inside a table.

if (option.equals("Download all records.")) {
    Statement stmt = conn.createStatement();
    ResultSet records = stmt.executeQuery("SELECT * FROM USER_INFO");

    try {
        while (records.next()) {
            if (un.equals(records.getString("username")))
                document.add(new Paragraph("*" + records.getString("username") + ", " + records.getString("role")));
            else
                document.add(new Paragraph(records.getString("username") + ", " + records.getString("role")));
        }

    } catch (DocumentException ex) {
        Logger.getLogger(CreatePdf.class.getName()).log(Level.SEVERE, null, ex);
    }

} else {
    PreparedStatement stmt = conn.prepareStatement("SELECT * FROM USER_INFO WHERE USERNAME =?");
    stmt.setString(1, un);
    ResultSet rs = stmt.executeQuery();

    while (rs.next()) {
        document.add(new Paragraph(rs.getString("username") + ", " + rs.getString("role")));
    }
}

document.add(new Paragraph(footer));
document.close();

}
catch (SQLException ex) {
    Logger.getLogger(CreatePdf.class.getName()).log(Level.SEVERE, null, ex);
}

I want the format of my table to look like this

username role
user1 pass1
so on... so on...
1

There are 1 best solutions below

0
On

Instead of adding the content of the records to the document immediately, create a Table (iText 7) or PdfPTable (iText 5) first, and add the content of the records as cells to the table. When all the records are added, add the table to the document.

iText 7

At the start of your code, create a table:

Table table = new Table(2);

Any (visual) properties of the table, such as alignment, width and borders, can be configured on the Table instance.

Instead of adding Paragraphs to the document, add Cells to the table:

table.addCell(new Cell().add(new Paragraph(records.getString("username"))));
table.addCell(new Cell().add(new Paragraph(records.getString("role"))));

Finally, add the table to the document:

document.add(table);
document.add(new Paragraph(footer));

iText 5

For iText 5, it's very similar:

PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell();
cell.addElement(new Paragraph(records.getString("username")));
table.addCell(cell);
PdfPCell cell2 = new PdfPCell();
cell2.addElement(new Paragraph(records.getString("role")));
table.addCell(cell2);
document.add(table);
document.add(new Paragraph(footer));