使用iText,我必须创建一个带有大PdfPTable的PDF,并在页脚上创建总页数(类似于'Y页的X')。我看了this例子,但我真的不明白它是如何工作的。目前我的代码是这样的:
PdfPTable table = new PdfPTable(10);
//something to fill the table
baos = new ByteArrayOutputStream();
document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
PdfTemplate totalPage = writer.getDirectContent().createTemplate(30, 16);
ColumnText columnTable = new ColumnText(writer.getDirectContent());
columnTable.addElement(table);
while(true) {
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, new Phrase("Pag. " + String.format("%d", writer.getPageNumber()),FONT_N), (document.right() - document.left())/ 2 + document.leftMargin(), document.bottom(), 0);
//I think something to insert totalPage in the document...
columnTable.setSimpleColumn(document.left(), document.top(), document.right(), Math.round(document.bottom()*1.5));
if(!ColumnText.hasMoreText(columnTable.go()))
break;
document.newPage();
}
//I think something to set totalPage...
document.close();
有人可以帮助我吗?
答案 0 :(得分:0)
使用以下代码替换while循环:
ColumnText columnTable = new ColumnText(writer.getDirectContent());
columnTable.addElement(table);
PdfTemplate totalPage = writer.getDirectContent().createTemplate(30, 16);
try {
table.setWidths(new int[]{24, 24, 2 });
table.setTotalWidth(527);
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(20);
table.getDefaultCell().setBorder(Rectangle.BOTTOM);
table.addCell("");
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(String.format("Page %d of", writer.getPageNumber()));
PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
cell.setBorder(Rectangle.BOTTOM);
table.addCell(cell);
table.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT,
new Phrase( String.valueOf(writer.getPageNumber())),
0, 0, 0);
}
catch(DocumentException de) {
throw new ExceptionConverter(de);
}