PdfPageEventHelper in iText

2019-02-28 14:16发布

问题:

I am creating a pdf where the title of each pdf page would be customized based on the current page number. For example, in the 1st page the title is "First Page", and in the 2nd page the title is "Second Page", and so on...

What we do now is we add the title to a PdfPTable, then we add a lot of other stuff to the PdfPTable as well, so this PdfPTable contains several pages of data. Finally we add this large PdfPTable object to document. Now we want to use the onStartPage() method in PdfPageEventHelper to get the current page number so that we can customize the title for each page.

The problem is onStartPage() does not trigger until we add that large PdfPTable object to the document, which means we cannot make the resource bundle to load different key values before the PdfPTable object is added to the document, right? Any suggestion to realize this?

--------------------we have codes like below-------------------------------------

  Phrase title = new Phrase();
  title.add(new Chunk(bundle.getString(pdfNewPageEventHandler.getKey()), headerFont));
  PdfPCell cell = new PdfPCell(new Paragraph(
            new Phrase(title)));
  .........
  PdfPTable table = new PdfPTable(tableSize);
  table.addCell(cell);
  .........
  document.add(table);




private class PdfNewPageEventHandler extends PdfPageEventHelper {

    private int currentPageNum = 0;
    private String key;

    @Override
    public void onStartPage(PdfWriter writer, Document document) {

        currentPageNum = currentPageNum + 1;

        if (currentPageNum == 1) {
            key = "firstPage";
        } 
        else if (currentPageNum == 2) {
            key = "secondPage";
        }

    }

    public String getKey() {
        return key;
    }

}

回答1:

I have more than one answer. I don't know which one applies to your specific situation:

  1. Don't ever add content in the onStartPage() method. As documented, all content should be added in the onEndPage() method.

  2. It's not always wise to create one large table (it builds up in memory) and then add the table to the document (only at this moment, memory can be freed). Maybe you want to try out some of the large table strategies from the documentation.

  3. In some cases, building a table in memory and then adding it to the document is the only strategy you can use. iText will then distribute the content of the table over different pages, triggering page events. However: if you want to trigger events that are specific to the table, you can also define events at the level of the table. There's a PdfPTableEventSplit and a PdfPTableEventAfterSplit class for this exact purpose.

The code sample you provided, didn't really illustrate the problem. Can you please rephrase the problem, as I'm not sure if any of my answers go to the core of the problem.



标签: java pdf itext