【问题标题】:How can I add a header to a PDF file using iText in C#?如何在 C# 中使用 iText 向 PDF 文件添加标题?
【发布时间】:2010-12-29 10:15:44
【问题描述】:

我正在尝试使用 iText 创建 PDF。我正在尝试添加一个将出现在每个页面上的标题,但我想添加一些文本,例如每个页面都不同的报告名称。我怎么解决这个问题?如果你不明白我想问什么,请看下面的例子:

在第 1 页

报告名称:测试报告 Emp_id Emp_Name Emp_sal ----- ----- ------ ----- ----- ------ ----- ----- ------

在第 2 页

Emp_id Emp_Name Emp_sal ----- ----- ------ ----- ----- ------ ----- ----- ------

注意:在第 2 页中,“报告名称”没有重复。

【问题讨论】:

  • 你知道如何创建一个新页面吗?如果你这样做了,那么只需在新页面的开头添加你需要的部分。

标签: c# pdf pdf-generation itextsharp


【解决方案1】:

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

    }
}

类似的东西。它可以被简化,因为我从一个页面事件中提取了它,该事件做了更多的事情,例如添加水印和自定义页眉和页脚。

【讨论】:

  • 那应该做得很好。 Bhaskara 可能需要调整页边距来为页眉保留足够的空间,但除此之外你应该很高兴。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多