问题
I have an application that I want to print an invoice like document in a table setup. Each line in the table will be from a separate document from a database. The iteration through the Db is not an issue but I want it to display something like this:
I can determine the total number of lines in the table in advance if that makes any difference. Does anyone have a piece of code to use as a starting point?
回答1:
Please take a look at the SimpleTable11 example and the PDF that is created when you run that code: simple_table11.pdf
As you need different types of PdfPCell
instance (without/with thick border, with/without, colspan, left/right aligned), you will benefit from writing a helper method:
public PdfPCell createCell(String content, float borderWidth, int colspan, int alignment) {
PdfPCell cell = new PdfPCell(new Phrase(content));
cell.setBorderWidth(borderWidth);
cell.setColspan(colspan);
cell.setHorizontalAlignment(alignment);
return cell;
}
Using this method will make your code easier to read and maintain.
This is how we create the document and add the table:
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
PdfPTable table = new PdfPTable(5);
table.setWidths(new int[]{1, 2, 1, 1, 1});
table.addCell(createCell("SKU", 2, 1, Element.ALIGN_LEFT));
table.addCell(createCell("Description", 2, 1, Element.ALIGN_LEFT));
table.addCell(createCell("Unit Price", 2, 1, Element.ALIGN_LEFT));
table.addCell(createCell("Quantity", 2, 1, Element.ALIGN_LEFT));
table.addCell(createCell("Extension", 2, 1, Element.ALIGN_LEFT));
String[][] data = {
{"ABC123", "The descriptive text may be more than one line and the text should wrap automatically", "$5.00", "10", "$50.00"},
{"QRS557", "Another description", "$100.00", "15", "$1,500.00"},
{"XYZ999", "Some stuff", "$1.00", "2", "$2.00"}
};
for (String[] row : data) {
table.addCell(createCell(row[0], 1, 1, Element.ALIGN_LEFT));
table.addCell(createCell(row[1], 1, 1, Element.ALIGN_LEFT));
table.addCell(createCell(row[2], 1, 1, Element.ALIGN_RIGHT));
table.addCell(createCell(row[3], 1, 1, Element.ALIGN_RIGHT));
table.addCell(createCell(row[4], 1, 1, Element.ALIGN_RIGHT));
}
table.addCell(createCell("Totals", 2, 4, Element.ALIGN_LEFT));
table.addCell(createCell("$1,552.00", 2, 1, Element.ALIGN_RIGHT));
document.add(table);
document.close();
}
As you indicated that you already have the code to loop over the records in a database, I mimicked those records using a two-dimensional String
array.
There is much more to say about tables, but before you post any further questions, please read the section about Tables and Table events in the free ebook The Best iText Question on StackOverflow.
来源:https://stackoverflow.com/questions/31146249/how-to-set-up-a-table-display-in-itextpdf