添加页眉和页脚使用iTextSharp的PDF [英] Add Header and Footer for PDF using iTextsharp

查看:556
本文介绍了添加页眉和页脚使用iTextSharp的PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么可以添加页眉和页脚在PDF中的每一页。

头球将仅包含一个文本
页脚将包含PDF文本和分页(页:4 1)

这怎么可能?我尝试添加下面的线,但头不以PDF格式显示出来。

  document.AddHeader(头,头文字);

这在code我使用PDF生成:

 保护无效GeneratePDF_Click(对象发件人,EventArgs的发送)
    {
        DataTable的DT =的getData();            Response.ContentType =应用程序/ PDF
            Response.AddHeader(内容处置,附件;文件名= Locations.pdf);
            Response.Cache.SetCacheability(HttpCacheability.NoCache);            文档的文档=新的文件();            PdfWriter.GetInstance(文件,Response.OutputStream);            document.Open();            iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.COURIER,8);            PdfPTable表=新PdfPTable(dt.Columns.Count);
            PdfPRow排= NULL;
            浮动[] =宽度新的浮动[] {1207米,1207米,2F,4F,2F};            table.SetWidths(宽度);            table.WidthPercentage = 100;
            INT ICOL = 0;
            字符串colname需要=;
            PdfPCell电池=新PdfPCell(新词(位置));            cell.Colspan = dt.Columns.Count;            的foreach(在dt.Columns的DataColumn C)
            {                table.AddCell(新乐句(c.ColumnName,font5));
            }            的foreach(在dt.Rows的DataRow R)
            {
                如果(dt.Rows.Count大于0)
                {
                    table.AddCell(新乐句(R [0]的ToString(),font5));
                    table.AddCell(新乐句(R [1]的ToString(),font5));
                    table.AddCell(新乐句(R [2]的ToString(),font5));
                    table.AddCell(新乐句(R [3]的ToString(),font5));
                    table.AddCell(新乐句(R [4]的ToString(),font5));
                }
            }
            document.Add(表);
            document.Close();            的Response.Write(文件);
            到Response.End();
        }
    }


解决方案

正如@Bruno已经回答了你需要使用pageEvents。

请查看下面的示例code:

 私人无效CreatePDF()
        {
            字符串文件名=的String.Empty;            日期时间fileCreationDatetime = DateTime.Now;            文件名=的String.Format({0} .PDF,fileCreationDatetime.ToString(@年月日)+_+ fileCreationDatetime.ToString(@HHMMSS));            字符串pdfPath =使用Server.Mappath(@〜\\ PDF文件\\)+文件名;            使用(的FileStream msReport =新的FileStream(pdfPath,FileMode.Create))
            {
                //步骤1
                使用(文档pdfDoc =新的文件(PageSize.A4,10F,10F,140F,10F))
                {
                    尝试
                    {
                        // 第2步
                        PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc,msReport);
                        pdfWriter.PageEvent =新Common.ITextEvents();                        //打开流
                        pdfDoc.Open();                        的for(int i = 0;我小于10;我++)
                        {
                            para段落=新段(世界,你好检查页眉页脚,新的字体(Font.FontFamily.HELVETICA,22));                            para.Alignment = Element.ALIGN_CENTER;                            pdfDoc.Add(对位);                            pdfDoc.NewPage();
                        }                        pdfDoc.Close();                    }
                    赶上(异常前)
                    {
                        //处理异常
                    }                    最后
                    {
                    }                }            }
        }

和创建一个名为ITextEvents.cs一个类文件,并添加以下code:

 公共类ITextEvents:PdfPageEventHelper
    {        //这是作家的contentbyte对象
        PdfContentByte CB;        //我们就会把页面的最终数目在模板
        PdfTemplate HeaderTemplate中,footerTemplate;        //这是我们将要使用的页眉/页脚的BASEFONT
        BASEFONT BF = NULL;        //这个跟踪的创建时间
        日期时间PrintTime = DateTime.Now;
        #地区字段
        私人字符串_header;
        #endregion        #区域属性
        公共字符串头
        {
            {返回_header; }
            集合{_header =价值; }
        }
        #endregion
        公共覆盖无效OnOpenDocument(PdfWriter作家,文档文件)
        {
            尝试
            {
                PrintTime = DateTime.Now;
                BF = BaseFont.CreateFont(BaseFont.HELVETICA,BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
                CB = writer.DirectContent;
                HeaderTemplate中= cb.CreateTemplate(100,100);
                footerTemplate = cb.CreateTemplate(50,50);
            }
            赶上(DocumentException德)
            {            }
            赶上(System.IO.IOException IOE)
            {            }
        }        公共覆盖无效的OnEndPage(iTextSharp.text.pdf.PdfWriter作家,iTextSharp.text.Document文件)
        {
            base.OnEndPage(作家,文件);            iTextSharp.text.Font baseFontNormal =新iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA,12F,iTextSharp.text.Font.NORMAL,iTextSharp.text.BaseColor.BLACK);            iTextSharp.text.Font baseFontBig =新iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA,12F,iTextSharp.text.Font.BOLD,iTextSharp.text.BaseColor.BLACK);            短语p1Header =新词(样本头在这里,ba​​seFontNormal);            //创建PdfTable对象
            PdfPTable pdfTab =新PdfPTable(3);            //我们必须创建单独的细胞,包括形象标志和2个独立的字符串
            //第1行
            PdfPCell pdfCell1 =新PdfPCell();
            PdfPCell pdfCell2 =新PdfPCell(p1Header);
            PdfPCell pdfCell3 =新PdfPCell();
            字符串文本=页面+ writer.PageNumber +的;
            //添加分页标题
            {
                cb.BeginText();
                cb.SetFontAndSize(BF,12);
                cb.SetTextMatrix(document.PageSize.GetRight(200),document.PageSize.GetTop(45));
                cb.ShowText(文本);
                cb.EndText();
                浮LEN = bf.GetWidthPoint(文字,12);
                //添加12在12页1
                cb.AddTemplate(HeaderTemplate中,document.PageSize.GetRight(200)+ LEN,document.PageSize.GetTop(45));
            }
            //添加分页页脚
            {
                cb.BeginText();
                cb.SetFontAndSize(BF,12);
                cb.SetTextMatrix(document.PageSize.GetRight(180),document.PageSize.GetBottom(30));
                cb.ShowText(文本);
                cb.EndText();
                浮LEN = bf.GetWidthPoint(文字,12);
                cb.AddTemplate(footerTemplate,document.PageSize.GetRight(180)+ LEN,document.PageSize.GetBottom(30));
            }
            // 2行
            PdfPCell pdfCell4 =新PdfPCell(新词(子标题描述,baseFontNormal));
            // 3行
            PdfPCell pdfCell5 =新PdfPCell(新词(日期:+ PrintTime.ToShortDateString(),baseFontBig));
            PdfPCell pdfCell6 =新PdfPCell();
            PdfPCell pdfCell7 =新PdfPCell(新词(TIME+的String.Format({0:T】,DateTime.Now),baseFontBig));
            //设置所有三个单元格对齐,并设置边框为0
            pdfCell1.Horizo​​ntalAlignment = Element.ALIGN_CENTER;
            pdfCell2.Horizo​​ntalAlignment = Element.ALIGN_CENTER;
            pdfCell3.Horizo​​ntalAlignment = Element.ALIGN_CENTER;
            pdfCell4.Horizo​​ntalAlignment = Element.ALIGN_CENTER;
            pdfCell5.Horizo​​ntalAlignment = Element.ALIGN_CENTER;
            pdfCell6.Horizo​​ntalAlignment = Element.ALIGN_CENTER;
            pdfCell7.Horizo​​ntalAlignment = Element.ALIGN_CENTER;
            pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
            pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
            pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell4.Colspan = 3;            pdfCell1.Border = 0;
            pdfCell2.Border = 0;
            pdfCell3.Border = 0;
            pdfCell4.Border = 0;
            pdfCell5.Border = 0;
            pdfCell6.Border = 0;
            pdfCell7.Border = 0;
            //添加所有三个单元格为PdfTable
            pdfTab.AddCell(pdfCell1);
            pdfTab.AddCell(pdfCell2);
            pdfTab.AddCell(pdfCell3);
            pdfTab.AddCell(pdfCell4);
            pdfTab.AddCell(pdfCell5);
            pdfTab.AddCell(pdfCell6);
            pdfTab.AddCell(pdfCell7);            pdfTab.TotalWidth = document.PageSize.Width - 80F;
            pdfTab.WidthPercentage = 70;
            //pdfTab.Horizo​​ntalAlignment = Element.ALIGN_CENTER;
            // PdfTable呼叫WriteSelectedRows。这从PdfWriter在PdfTable写道行
            //第一个参数是起始行。 -1表示没有结束行,并包含所有行写
            //第三和第四个参数是x和y位置开始写作
            pdfTab.WriteSelectedRows(0,-1,40,document.PageSize.Height - 30,writer.DirectContent);
            //设置pdfContent值            //移动指针并从页面的其余部分画线分隔页眉节
            cb.MoveTo(40,document.PageSize.Height - 100);
            cb.LineTo(document.PageSize.Width - 40,document.PageSize.Height - 100);
            cb.Stroke();            //移动指针并画线,从页面的其余部分分开页脚部分
            cb.MoveTo(40,document.PageSize.GetBottom(50));
            cb.LineTo(document.PageSize.Width - 40,document.PageSize.GetBottom(50));
            cb.Stroke();
        }        公共覆盖无效OnCloseDocument(PdfWriter作家,文档文件)
        {
            base.OnCloseDocument(作家,文件);            headerTemplate.BeginText();
            headerTemplate.SetFontAndSize(BF,12);
            headerTemplate.SetTextMatrix(0,0);
            headerTemplate.ShowText((writer.PageNumber - 1)的ToString());
            headerTemplate.EndText();            footerTemplate.BeginText();
            footerTemplate.SetFontAndSize(BF,12);
            footerTemplate.SetTextMatrix(0,0);
            footerTemplate.ShowText((writer.PageNumber - 1)的ToString());
            footerTemplate.EndText();
        }
    }

我希望它能帮助!

How can I add header and footer for each page in the pdf.

Headed will contain just a text Footer will contain a text and pagination for pdf (Page : 1 of 4)

How is this possible ? I tried to add the below line, but header does not show up in pdf.

document.AddHeader("Header", "Header Text");

This the code I am using for generation PDF :

   protected void GeneratePDF_Click(object sender, EventArgs e)
    {
        DataTable dt = getData(); 

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Locations.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            Document document = new Document();

            PdfWriter.GetInstance(document, Response.OutputStream);

            document.Open();

            iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.COURIER , 8);

            PdfPTable table = new PdfPTable(dt.Columns.Count);
            PdfPRow row = null;
            float[] widths = new float[] { 6f, 6f, 2f, 4f, 2f };

            table.SetWidths(widths);

            table.WidthPercentage = 100;
            int iCol = 0;
            string colname = "";
            PdfPCell cell = new PdfPCell(new Phrase("Locations"));

            cell.Colspan = dt.Columns.Count;

            foreach (DataColumn c in dt.Columns)
            {

                table.AddCell(new Phrase(c.ColumnName, font5));
            }

            foreach (DataRow r in dt.Rows)
            {
                if (dt.Rows.Count > 0)
                {
                    table.AddCell(new Phrase(r[0].ToString(), font5));
                    table.AddCell(new Phrase(r[1].ToString(), font5));
                    table.AddCell(new Phrase(r[2].ToString(), font5));
                    table.AddCell(new Phrase(r[3].ToString(), font5));
                    table.AddCell(new Phrase(r[4].ToString(), font5));
                }
            }
            document.Add(table);
            document.Close();

            Response.Write(document);
            Response.End();
        } 
    }

解决方案

As already answered by @Bruno you need to use pageEvents.

Please check out the sample code below:

private void CreatePDF()
        {
            string fileName = string.Empty;

            DateTime fileCreationDatetime = DateTime.Now;

            fileName = string.Format("{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_" + fileCreationDatetime.ToString(@"HHmmss"));

            string pdfPath = Server.MapPath(@"~\PDFs\") +   fileName;

            using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
            {
                //step 1
                using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f))
                {
                    try
                    {
                        // step 2
                        PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
                        pdfWriter.PageEvent = new Common.ITextEvents();

                        //open the stream 
                        pdfDoc.Open();

                        for (int i = 0; i < 10; i++)
                        {
                            Paragraph para = new Paragraph("Hello world. Checking Header Footer", new Font(Font.FontFamily.HELVETICA, 22));

                            para.Alignment = Element.ALIGN_CENTER;

                            pdfDoc.Add(para);

                            pdfDoc.NewPage();
                        }

                        pdfDoc.Close();

                    }
                    catch (Exception ex)
                    {
                        //handle exception
                    }

                    finally
                    {


                    }

                }

            }
        }

And create one class file named ITextEvents.cs and add following code:

public class ITextEvents : PdfPageEventHelper
    {

        // This is the contentbyte object of the writer
        PdfContentByte cb;

        // we will put the final number of pages in a template
        PdfTemplate headerTemplate, footerTemplate;

        // this is the BaseFont we are going to use for the header / footer
        BaseFont bf = null;

        // This keeps track of the creation time
        DateTime PrintTime = DateTime.Now;


        #region Fields
        private string _header;
        #endregion

        #region Properties
        public string Header
        {
            get { return _header; }
            set { _header = value; }
        }
        #endregion


        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            try
            {
                PrintTime = DateTime.Now;
                bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                cb = writer.DirectContent;
                headerTemplate = cb.CreateTemplate(100, 100);
                footerTemplate = cb.CreateTemplate(50, 50);
            }
            catch (DocumentException de)
            {

            }
            catch (System.IO.IOException ioe)
            {

            }
        }

        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            base.OnEndPage(writer, document);

            iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

            iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);

            Phrase p1Header = new Phrase("Sample Header Here", baseFontNormal);

            //Create PdfTable object
            PdfPTable pdfTab = new PdfPTable(3);

            //We will have to create separate cells to include image logo and 2 separate strings
            //Row 1
            PdfPCell pdfCell1 = new PdfPCell();
            PdfPCell pdfCell2 = new PdfPCell(p1Header);
            PdfPCell pdfCell3 = new PdfPCell();
            String text = "Page " + writer.PageNumber + " of ";


            //Add paging to header
            {
                cb.BeginText();
                cb.SetFontAndSize(bf, 12);
                cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
                cb.ShowText(text);
                cb.EndText();
                float len = bf.GetWidthPoint(text, 12);
                //Adds "12" in Page 1 of 12
                cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
            }
            //Add paging to footer
            {
                cb.BeginText();
                cb.SetFontAndSize(bf, 12);
                cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
                cb.ShowText(text);
                cb.EndText();
                float len = bf.GetWidthPoint(text, 12);
                cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));
            }
            //Row 2
            PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal));
            //Row 3


            PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig));
            PdfPCell pdfCell6 = new PdfPCell();
            PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig));


            //set the alignment of all three cells and set border to 0
            pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;


            pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
            pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
            pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;


            pdfCell4.Colspan = 3;



            pdfCell1.Border = 0;
            pdfCell2.Border = 0;
            pdfCell3.Border = 0;
            pdfCell4.Border = 0;
            pdfCell5.Border = 0;
            pdfCell6.Border = 0;
            pdfCell7.Border = 0;


            //add all three cells into PdfTable
            pdfTab.AddCell(pdfCell1);
            pdfTab.AddCell(pdfCell2);
            pdfTab.AddCell(pdfCell3);
            pdfTab.AddCell(pdfCell4);
            pdfTab.AddCell(pdfCell5);
            pdfTab.AddCell(pdfCell6);
            pdfTab.AddCell(pdfCell7);

            pdfTab.TotalWidth = document.PageSize.Width - 80f;
            pdfTab.WidthPercentage = 70;
            //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER;


            //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
            //first param is start row. -1 indicates there is no end row and all the rows to be included to write
            //Third and fourth param is x and y position to start writing
            pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);
            //set pdfContent value

            //Move the pointer and draw line to separate header section from rest of page
            cb.MoveTo(40, document.PageSize.Height - 100);
            cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
            cb.Stroke();

            //Move the pointer and draw line to separate footer section from rest of page
            cb.MoveTo(40, document.PageSize.GetBottom(50) );
            cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
            cb.Stroke();
        }

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);

            headerTemplate.BeginText();
            headerTemplate.SetFontAndSize(bf, 12);
            headerTemplate.SetTextMatrix(0, 0);
            headerTemplate.ShowText((writer.PageNumber - 1).ToString());
            headerTemplate.EndText();

            footerTemplate.BeginText();
            footerTemplate.SetFontAndSize(bf, 12);
            footerTemplate.SetTextMatrix(0, 0);
            footerTemplate.ShowText((writer.PageNumber - 1).ToString());
            footerTemplate.EndText();


        }
    }

I hope it helps!

这篇关于添加页眉和页脚使用iTextSharp的PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆