0
votes

I need to add an HTML block as the header of all pages using iText7. The header contains an image logo and some text.

I have this at the moment, before closing the document object:

for (int i = 1; i <= n; i++)
{
    float x = pdf.GetPage(i).GetPageSize().GetWidth() / 2;  // 297.5f
    float yFooter = 20;

    if (headerBlock != null)
    {
        float yHeader = 600;// pdf.GetPage(i).GetPageSize().GetTop() - 20;

        // Header
        document.ShowTextAligned(headerBlock, 0, yHeader, page, TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0);
    }

    // Footer
    Paragraph footerBlock = new Paragraph(String.Format("Página {0} de {1}", i, n));
    document.ShowTextAligned(footerBlock, x, yFooter, page, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 0);
}

Footer works correctly but header.

Header was loaded this way:

Paragraph headerBlock = String.IsNullOrWhiteSpace(header) ? null : CreateHtmlParagraph(header);

where, CreateHtmlParagraph is defined this way:

private Paragraph CreateHtmlParagraph(string html)
{
    Paragraph p = new Paragraph();
    ConverterProperties properties = new ConverterProperties();
    properties.SetBaseUri(HttpContext.Current.Server.MapPath("/"));
    var elements = HtmlConverter.ConvertToElements(html, properties);

    foreach (IElement e in elements)
        p.Add((IBlockElement)e);

    return p;
}

When I add the header using the document.Add method, it works well, but for the first page only. All other content follows it.

When I try to add it using ShowTextAligned method, only the image is rendered in all pages.

By the way, is there a way to get the actual height of the header paragraph? I think, once the header positioning is solved, I will have the problem that the other content blocks will be overlapped by the header.

1

1 Answers

0
votes

I believe you need to use page events. This is well documented. Create a class that implements IEventHandler that will handle specific events.

Add a event handler for a specific event

pdf.AddEventHandler(PdfDocumentEvent.START_PAGE, new StartPageEventHandler());

StartPageEventHandler is a class you create, implementing IEventHandler. You'll likely need to take this approach for both header and footer.

See this link for more info