Adding header and footer to PDF documents with C# and .NET

With SautinSoft.Pdf, you can add a header and footer to PDF from your C# or VB.NET application.

The following example shows how you can easily add a header and footer to an existing PDF file.

Полный код

using System;
using System.Globalization;
using System.IO;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Header and Footer.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/header-footer.php
        /// </remarks>
        static void Main(string[] args)
        {
            // Before starting this example, please get a free 100-day trial key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // PdfDocument.SetLicense("...");

            string pdfFile = Path.GetFullPath(@"..\..\..\simple text.pdf");

            using (var document = PdfDocument.Load(pdfFile))
            {
                double marginLeft = 20, marginTop = 10, marginRight = 20, marginBottom = 10;

                using (var formattedText = new PdfFormattedText())
                {
                    formattedText.Append(DateTime.Now.ToString(CultureInfo.InvariantCulture));

                    // Add a header with the current date and time to all pages.
                    foreach (var page in document.Pages)
                    {
                        // Set the location of the bottom-left corner of the text.
                        // We want the top-left corner of the text to be at location (marginLeft, marginTop)
                        // from the top-left corner of the page.
                        // NOTE: In PDF, location (0, 0) is at the bottom-left corner of the page
                        // and the positive y axis extends vertically upward.
                        double x = marginLeft, y = page.CropBox.Top - marginTop - formattedText.Height;

                        page.Content.DrawText(formattedText, new PdfPoint(x, y));
                    }

                    // Add a footer with the current page number to all pages.
                    int pageCount = document.Pages.Count, pageNumber = 0;
                    foreach (var page in document.Pages)
                    {
                        ++pageNumber;

                        formattedText.Clear();
                        formattedText.Append(string.Format("Page {0} of {1}", pageNumber, pageCount));

                        // Set the location of the bottom-left corner of the text.
                        double x = page.CropBox.Width - marginRight - formattedText.Width, y = marginBottom;

                        page.Content.DrawText(formattedText, new PdfPoint(x, y));
                    }
                }

                document.Save("Header and Footer.pdf");
            }

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("Header and Footer.pdf") { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.Globalization
Imports System.IO
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Header and Footer.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/header-footer.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			' Before starting this example, please get a free 100-day trial key:
			' https://sautinsoft.com/start-for-free/

			' Apply the key here:
			' PdfDocument.SetLicense("...");

			Dim pdfFile As String = Path.GetFullPath("..\..\..\simple text.pdf")

			Using document = PdfDocument.Load(pdfFile)
				Dim marginLeft As Double = 20, marginTop As Double = 10, marginRight As Double = 20, marginBottom As Double = 10

				Using formattedText = New PdfFormattedText()
					formattedText.Append(DateTime.Now.ToString(CultureInfo.InvariantCulture))

					' Add a header with the current date and time to all pages.
					For Each page In document.Pages
						' Set the location of the bottom-left corner of the text.
						' We want the top-left corner of the text to be at location (marginLeft, marginTop)
						' from the top-left corner of the page.
						' NOTE: In PDF, location (0, 0) is at the bottom-left corner of the page
						' and the positive y axis extends vertically upward.
						Dim x As Double = marginLeft, y As Double = page.CropBox.Top - marginTop - formattedText.Height

						page.Content.DrawText(formattedText, New PdfPoint(x, y))
					Next page

					' Add a footer with the current page number to all pages.
					Dim pageCount As Integer = document.Pages.Count, pageNumber As Integer = 0
					For Each page In document.Pages
						pageNumber += 1

						formattedText.Clear()
						formattedText.Append(String.Format("Page {0} of {1}", pageNumber, pageCount))

						' Set the location of the bottom-left corner of the text.
						Dim x As Double = page.CropBox.Width - marginRight - formattedText.Width, y As Double = marginBottom

						page.Content.DrawText(formattedText, New PdfPoint(x, y))
					Next page
				End Using

				document.Save("Header and Footer.pdf")
			End Using

			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("Header and Footer.pdf") With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.