繁体   English   中英

使用iText7将标题添加到页面

[英]Adding header to pages using iText7

我需要使用iText7将HTML块添加为所有页面的标题。 标头包含图像徽标和一些文本。

在关闭文档对象之前,我现在有这个:

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);
}

页脚正常工作,但页眉。

标头以这种方式加载:

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

其中, CreateHtmlParagraph的定义方式如下:

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;
}

当我使用document.Add方法添加标题时,它可以很好地工作,但仅适用于第一页。 其他所有内容均紧随其后。

当我尝试使用ShowTextAligned方法添加它时,在所有页面中仅呈现图像。

顺便说一句,有没有一种方法可以获取标题段的实际高度? 我认为,一旦解决了标头定位问题,我就会遇到其他内容块被标头覆盖的问题。

我相信您需要使用页面事件。 这是有据可查的。 创建一个实现IEventHandler的类,该类将处理特定事件。

为特定事件添加事件处理程序

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

StartPageEventHandler是您创建的实现IEventHandler的类。 您可能需要对页眉和页脚都采用这种方法。

查看此链接以获取更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM