iTextSharp在onendpage中为文档中的第一页设置标题

时间:2017-03-20 11:01:05

标签: c# asp.net itext

如何将标题设置为仅在文档的第一页上。

如下所示在每一页上设置它。

private class PDFAddHeaderTopOnly : PdfPageEventHelper
{
     public PDFAddHeaderTopOnly(string html)
     {
         this.html = html;
     }

     public override void OnEndPage(PdfWriter writer, Document document)
     {
         base.OnEndPage(writer, document);
         ColumnText ct = new ColumnText(writer.DirectContent);
         XMLWorkerHelper.GetInstance().ParseXHtml(new ColumnTextElementHandler(ct), new StringReader(html));
         ct.SetSimpleColumn(document.Left, document.Top, document.Right, document.GetTop(-PDFMarginTop), 0, Element.ALIGN_MIDDLE);
         ct.Go();
     }

     string html = null;
}

1 个答案:

答案 0 :(得分:2)

一般

如果您只想在第一页上执行某些操作,只需在打开文档后将其作为第一个操作,并且不要尝试将其压缩到专为重复性任务设计的页面事件框架中。

在您的情况下

您最有可能使用这样的PDFAddHeaderTopOnly课程:

string html = ...;

using (Document document = new Document()) {
    PdfWriter writer = PdfWriter.GetInstance(document, stream);
    writer.PageEvent = new PDFAddHeaderTopOnly(html);       
    document.Open();
    [Add some content to document]
}

如果您只想在第一页上显示标题,请执行以下操作:

using (Document document = new Document()) {
    PdfWriter writer = PdfWriter.GetInstance(document, stream);
    document.Open();

    // Draw first-page-only header
    ColumnText ct = new ColumnText(writer.DirectContent);
    XMLWorkerHelper.GetInstance().ParseXHtml(new ColumnTextElementHandler(ct), new StringReader(html));
    ct.SetSimpleColumn(document.Left, document.Top, document.Right, document.GetTop(-PDFMarginTop), 0, Element.ALIGN_MIDDLE);
    ct.Go();

    // Draw document content
    [Add some content to document]
}