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... |
Instead of adding the content of the records to the
document
immediately, create aTable
(iText 7) orPdfPTable
(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:
Any (visual) properties of the table, such as alignment, width and borders, can be configured on the
Table
instance.Instead of adding
Paragraph
s to thedocument
, addCell
s to thetable
:Finally, add the table to the document:
iText 5
For iText 5, it's very similar: