Handling table counter on specific page

I am working with itext7 library. I want to make table counter which will positioned on top of the table. The problem is on every last page where table is contained. It draws the number of next table.This is result. You can see where table1 is ending but top of table is 2 etc.

public class TabPageHandler : IEventHandler
{
    public string number { get; set; }
    public TabPageHandler(string number)
    {
        this.number = number;
    }


    public void HandleEvent(Event @event)
    {
        PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
        PdfDocument pdfDoc = docEvent.GetDocument();
        PdfPage page = docEvent.GetPage();
        int pageNumber = pdfDoc.GetPageNumber(page);

        PdfCanvas canvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);

        canvas.BeginText().MoveText(page.GetPageSize().GetWidth() / 2, page.GetPageSize().GetTop() - 35)
            .SetFontAndSize(PdfFontFactory.CreateFont(FontConstants.TIMES_ROMAN), 10)
            .ShowText("Number of page " + pageNumber)
            .EndText();

        canvas.BeginText().MoveText(20, page.GetPageSize().GetTop() - 20)
            .SetFontAndSize(PdfFontFactory.CreateFont(FontConstants.TIMES_ROMAN), 10)
            .ShowText("Table:" + number)
            .EndText();

        canvas.Release();
    }
}

public static void Main()
    {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
        Document doc = new Document(pdfDoc, PageSize.A4, true);
        for (int i = 1; i < 5; i++)
        {
            pdfDoc.RemoveAllHandlers();
            pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new TabPageHandler(i.ToString()));
            Table table = new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth();
            table.AddHeaderCell(new Paragraph(i.ToString()));
            for (int j = 0; j < 40 * i; j++)
            {
                table.AddCell(new Paragraph("aaa"));
            }
            doc.Add(table);
            doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        }
        doc.Close();
    }


Read more here: https://stackoverflow.com/questions/66995409/handling-table-counter-on-specific-page

Content Attribution

This content was originally published by niichan at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: