Method to Paginate PDF Document-Header and Footer Contained-with C#

Generally speaking, if a document has too many pages, we will add page numbers for it, which can be taken as header or footer. Also, we can add text or image as header or footer, for example, company name, article title, company logo and so on. In this post, I will show how to paginate PDF document with C#, including drawing headers and footer, setting page label.

In this example, I create a PDF document with several pages. I will paginate them and draw header and footer. At beginning, I add resources in my project, including contents, image description and title, which will be used in document creation. Also, I use a .NET PDF Component, Spire.PDF for .NET to meet my requirement so that I add its dll file as reference.

The following steps show details.

  1. Create a PDF document and set margin for it.
  2. Draw document cover. Firstly, add page number and set its style. Set prefix as cover and then set page, including page size and margin. Add page and draw header and footer. Secondly, add title. Set format and location. Thirdly, add an image to be as cover. Set its location and then add description below this image. Fourthly, because contents and images are from wiki, so add references at the end of this page.
  3. Draw document contents. Add page number, prefix and set page as step 2. In resources, the contents are not formatted. In this step, I format contents, including font style, line space and paragraph indent for each line. Finally, set layout for contents.
  4. Draw header and footer. Add header and footer image at first. Set their location and transparency. Then, add text header and format it.
  5. Draw page numbers as footer and format it.
  6. Save and launch file.

Main Coding:

using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Text;

namespace PDF_Paginate
{
    class paginate
    {
        static void Main(string[] args)
        {

            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            //Margin
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;
            DrawCover(doc.Sections.Add(), margin);
            DrawContent(doc.Sections.Add(), margin);
            DrawPageNumber(doc.Sections[1], margin, 1, doc.Sections[1].Pages.Count);

            //Save
            doc.SaveToFile(“Pagination.pdf”);
            doc.Close();

            //Launch
            System.Diagnostics.Process.Start(“Pagination.pdf”);
        }

        static void DrawCover(PdfSection section, PdfMargins margin)
        {
            section.PageNumber = new PdfPageNumber();
            section.PageNumber.NumberStyle = PdfNumberStyle.LowerLatin;
            section.PageNumber.Prefix = “cover “;
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Margins.All = 0;
            PdfPageBase page = section.Pages.Add();
            DrawPageHeaderAndFooter(page, margin, true);

            //Title
            PdfBrush brush1 = PdfBrushes.DarkRed;
            PdfBrush brush2 = PdfBrushes.DeepSkyBlue;
            PdfBrush brush3 = PdfBrushes.Blue;
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Center;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font(“Calibri”, 13f, FontStyle.Regular));
            float x = 0, y = 5;
            x = page.Canvas.ClientSize.Width / 2;
            y = y + margin.Top;
            page.Canvas.DrawString(“Chinese Lantern Festival”, font1, brush1, x, y, format);

            //Cover
            PdfBrush brush4 = new PdfSolidBrush(new PdfRGBColor(0xf9, 0xf9, 0xf9));
            PdfImage image
                = PdfImage.FromFile(@”D:\work\My Documents\Lantern.png”);
            String text = PDF_Paginate.Properties.Resources.ImageDescription;
            float r = image.PhysicalDimension.Height / image.Height;
            PdfPen pen = new PdfPen(brush1, r);
            SizeF size = font1.MeasureString(text, image.PhysicalDimension.Width – 2);
            PdfTemplate template
                = new PdfTemplate(image.PhysicalDimension.Width + 4 * r + 4,
                    image.PhysicalDimension.Height + 4 * r + 7 + size.Height);
            template.Graphics.DrawRectangle(pen, brush4, 0, 0, template.Width, template.Height);
            x = y = r + 2;
            template.Graphics.DrawRectangle(brush1, x, y,
                image.PhysicalDimension.Width + 2 * r,
                image.PhysicalDimension.Height + 2 * r);
            x = y = x + r;
            template.Graphics.DrawImage(image, x, y);
            x = x – 1;
            y = y + image.PhysicalDimension.Height + r + 2;
            template.Graphics.DrawString(text, font1, brush3,
                new RectangleF(new PointF(x, y), size));
            float x1 = (page.Canvas.ClientSize.Width – template.Width) / 2;
            float y1 = (page.Canvas.ClientSize.Height – margin.Top – margin.Bottom) * (1 – 0.618f) – template.Height / 2 + margin.Top;
            template.Draw(page.Canvas, x1, y1);

            //Reference
            PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font(“Times New Roman”, 8f));
            format.MeasureTrailingSpaces = true;
            String text1 = “(All text and picture from Wikipedia, the free encyclopedia”;
            x = x+margin.Left;
            y = y1 + template.Height + 10;
            page.Canvas.DrawString(text1, font2, brush2, x, y, format);
        }

        static void DrawContent(PdfSection section, PdfMargins margin)
        {
            section.PageNumber = new PdfPageNumber();
            section.PageNumber.NumberStyle = PdfNumberStyle.Numeric;
            section.PageNumber.Prefix = “page”;
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Margins.All = 0;
            PdfPageBase page = section.Pages.Add();
            DrawPageHeaderAndFooter(page, margin, false);
            float x = margin.Left;
            float y = margin.Top + 8;
            float width = page.Canvas.ClientSize.Width – margin.Left – margin.Right;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font(“Calibri”, 11f), true);
            PdfBrush brush1 = PdfBrushes.Black;
            PdfPen pen1 = new PdfPen(brush1, 0.55f);
            page.Canvas.DrawString(PDF_Paginate.Properties.Resources.Title, font1, brush1, x, y);
            y = y + font1.MeasureString(PDF_Paginate.Properties.Resources.Title).Height + 6;
            page.Canvas.DrawLine(pen1, x, y, page.Canvas.ClientSize.Width – margin.Right, y);
            y = y + 1.75f;
            String content = PDF_Paginate.Properties.Resources.Content;
            String[] lines
                = content.Split(new char[] { ‘\r’, ‘\n’ }, StringSplitOptions.RemoveEmptyEntries);
            PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font(“Calibri”, 10f, FontStyle.Regular), true);
            PdfStringFormat format1 = new PdfStringFormat();
            format1.MeasureTrailingSpaces = true;
            format1.LineSpacing = font2.Height * 1.5f;
            format1.ParagraphIndent = font2.MeasureString(“\t”, format1).Width;
            y = y + font2.Height * 0.5f;
            SizeF size = font2.MeasureString(lines[0], width, format1);
            page.Canvas.DrawString(lines[0], font2, brush1,
                new RectangleF(new PointF(x, y), size), format1);
            y = y + size.Height;
            PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font(“Calibri”, 10f), true);
            PdfStringFormat format2 = new PdfStringFormat();
            format2.LineSpacing = font3.Height * 1.4f;
            format2.MeasureTrailingSpaces = true;
            size = font3.MeasureString(lines[1], width, format2);
            page.Canvas.DrawString(lines[1], font3, brush1,
                new RectangleF(new PointF(x, y), size), format2);
            y = y + size.Height;
            y = y + font3.Height * 0.75f;
            float indent = font3.MeasureString(“\t\t”, format2).Width;
            float x1 = x + indent;
            size = font3.MeasureString(lines[2], width – indent, format2);
            page.Canvas.DrawString(lines[2], font3, brush1,
                new RectangleF(new PointF(x1, y), size), format2);
            y = y + size.Height + font3.Height * 0.75f;
            StringBuilder buff = new StringBuilder();
            for (int i = 3; i < lines.Length; i++)
            {
                buff.AppendLine(lines[i]);
            }
            content = buff.ToString();
            PdfStringLayouter textLayouter = new PdfStringLayouter();
            PdfStringLayoutResult result
                = textLayouter.Layout(content, font3, format2, new SizeF(width, float.MaxValue));
            foreach (LineInfo line in result.Lines)
            {
                if ((line.LineType & LineType.FirstParagraphLine) == LineType.FirstParagraphLine)
                {
                    y = y + font3.Height * 0.75f;
                }
                if (y > (page.Canvas.ClientSize.Height – margin.Bottom – result.LineHeight))
                {
                    page = section.Pages.Add();
                    DrawPageHeaderAndFooter(page, margin, false);
                    y = margin.Top;
                }
                page.Canvas.DrawString(line.Text, font3, brush1, x, y, format2);
                y = y + result.LineHeight;
            }
        }

        static void DrawPageHeaderAndFooter(PdfPageBase page, PdfMargins margin, bool isCover)
        {
            page.Canvas.SetTransparency(0.5f);
            PdfImage headerImage
                = PdfImage.FromFile(@”D:\work\My Documents\lanterndrawing.jpg”);
            PdfImage footerImage
                = PdfImage.FromFile(@”D:\work\My Documents\yuanxiao.gif”);
            page.Canvas.DrawImage(headerImage, new PointF(0, 0));
            page.Canvas.DrawImage(footerImage, new PointF(0, page.Canvas.ClientSize.Height – footerImage.PhysicalDimension.Height));
            if (isCover)
            {
                page.Canvas.SetTransparency(1);
                return;
            }
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 0.75f);
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font(“Calibri”, 9f, FontStyle.Regular), true);
            PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right);
            format.MeasureTrailingSpaces = true;
            float space = font.Height * 0.75f;
            float x = margin.Left;
            float width = page.Canvas.ClientSize.Width – margin.Left – margin.Right;
            float y = margin.Top – space;
            page.Canvas.DrawLine(pen, x, y, x + width, y);
            y = y – 1 – font.Height;
            page.Canvas.DrawString(“Chinese Lantern Festival”, font, brush, x + width, y, format);
            page.Canvas.SetTransparency(1);
        }

        static void DrawPageNumber(PdfSection section, PdfMargins margin, int startNumber, int pageCount)
        {
            foreach (PdfPageBase page in section.Pages)
            {
                page.Canvas.SetTransparency(0.5f);
                PdfBrush brush = PdfBrushes.Black;
                PdfPen pen = new PdfPen(brush, 0.75f);
                PdfTrueTypeFont font = new PdfTrueTypeFont(new Font(“Calibri”, 9f, FontStyle.Regular), true);
                PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right);
                format.MeasureTrailingSpaces = true;
                float space = font.Height * 0.75f;
                float x = margin.Left;
                float width = page.Canvas.ClientSize.Width – margin.Left – margin.Right;
                float y = page.Canvas.ClientSize.Height – margin.Bottom + space;
                page.Canvas.DrawLine(pen, x, y, x + width, y);
                y = y + 1;
                String numberLabel
                    = String.Format(“{0} of {1}”, startNumber++, pageCount);
                page.Canvas.DrawString(numberLabel, font, brush, x + width, y, format);
                page.Canvas.SetTransparency(1);
            }
        }
    }
}

Result Shown by Following:

Freely Download Spire.PDF for .NET

Advertisements

Author: janewdaisy

.NET Program Beginner. Share methods about how to use C#/VB.NET to export data, operate Word, Excel, PDF and other useful skills.

1 thought on “Method to Paginate PDF Document-Header and Footer Contained-with C#”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s