简体   繁体   English

如何在C#中使用iText将标头添加到PDF文件?

[英]How can I add a header to a PDF file using iText in C#?

I am trying to create a PDF using iText. 我正在尝试使用iText创建PDF。 I am trying to add a header that will appear on every page, but I want add some text like the report name that will be different for every page. 我正在尝试添加将出现在每个页面上的标题,但是我想添加一些文本,例如报告名称,每个页面都会有所不同。 How can I solve this problem? 我怎么解决这个问题? If you don't understand what I'm trying to ask, please see the example below: 如果您不明白我要问的问题,请参见以下示例:

In Page 1 在第1页

Report Name: Test Report

Emp_id  Emp_Name  Emp_sal 

-----    -----      ------
-----    -----      ------
-----    -----      ------

In Page 2 在第2页

Emp_id  Emp_Name  Emp_sal 

-----    -----      ------
-----    -----      ------
-----    -----      ------

Note: In Page 2, "Report Name" is not repeating. 注意:在第2页中,“报告名称”没有重复。

In iText 5 you can create custom headers using page events. 在iText 5中,您可以使用页面事件创建自定义标题。

using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace PDFLib.PageEvents
{ 
    public class CustomPageEvent : PdfPageEventHelper
    {
        private int _page;
        private readonly Rectangle _marges;
        private string _text;

        private static readonly Font FontHf = FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE, 9);

        private readonly Dictionary<int, float> _posicions;

        public CustomPageEvent(string text){
            _text = text;
            _marges = new Rectangle(10, 10, _pageSize.Width - 20, _pageSize.Height - 20);
            _posicions = new Dictionary<int, float>
                         {
                             {Element.ALIGN_LEFT, _marges.Left + 10},
                             {Element.ALIGN_RIGHT, _marges.Right - 10},
                             {Element.ALIGN_CENTER, (_marges.Left + _marges.Right)/2}
                         };
        }

        public override void OnStartPage(PdfWriter writer, Document document)
        {
            _page++;

            base.OnStartPage(writer, document);
        }

        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            _page = 0;
        }

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            if (page==1)
                ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, new Phrase(string.Format("{0}", _text), FontHf), _posicions[Element.ALIGN_CENTER], _marges.Top-10, 0);

            base.OnEndPage(writer,document);
        }

    }
}

Something like this. 这样的事情。 It can be simplified as I extracted this from a page event that did many more things as adding watermarks and custom headers and footers. 当我从页面事件中提取此内容时,它可以简化,它添加了水印以及自定义的页眉和页脚,还做了很多其他事情。

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

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