iText PDFWriter - Writing table header if the few table rows go to new page

对着背影说爱祢 提交于 2019-12-22 10:56:18

问题


I am using PdfWriter to create a PDF document. I am adding a PdfPTable to the PDF document. This table has header row and then actual data rows. If the table is big, then part of it gets carried forward to new page. I want this page to have table header row as well. However, I want this header row only when the table data goes on new page.


回答1:


This is how you create a table with a header row:

// table with 2 columns:
PdfPTable table = new PdfPTable(2);
// header row:
table.addCell("Key");
table.addCell("Value");
table.setHeaderRows(1);
// many data rows:
for (int i = 1; i < 51; i++) {
    table.addCell("key: " + i);
    table.addCell("value: " + i);
}
document.add(table);

In this case, the table needs more than one page. As you used setHeaderRows() with 1 as parameter, the first row will be repeated:

If you don't want the header to be present on the first page, you have to add a single line: table.setSkipFirstHeader(true);

// table with 2 columns:
PdfPTable table = new PdfPTable(2);
// header row:
table.addCell("Key");
table.addCell("Value");
table.setHeaderRows(1);
table.setSkipFirstHeader(true);
// many data rows:
for (int i = 1; i < 51; i++) {
    table.addCell("key: " + i);
    table.addCell("value: " + i);
}
document.add(table);

Now the table looks like this:



来源:https://stackoverflow.com/questions/32582927/itext-pdfwriter-writing-table-header-if-the-few-table-rows-go-to-new-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!