Add Header to Existing PDF in C#, VB.NET

In this article, you will learn how to add header to an existing PDF document using Spire.PDF. For a page in a ready-made PDF document, the coordinate system follows the following rules.

  • The origin of the PDF coordinate system (0, 0) represents the top-left corner of the PDF page.
  • The x-axis extends to the right and the y-axis extends downward.

Before you draw text or image at the specified coordinates in the empty space, you must measure the margins of the page yourself to prevent the header from overlapping the body.

Step 1: Load a sample PDF document.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("sample.pdf");

Step 2: Draw image in the top empty space of each page.

for (int i = 0; i < doc.Pages.Count; i++)
{
    PdfImage headerImage = PdfImage.FromFile("logo.png");
    float width = headerImage.Width / 3;
    float height = headerImage.Height / 3;
    doc.Pages[i].Canvas.DrawImage(headerImage, 85, 20, width, height);
}

Step 3: Draw text in the top empty space of each page.

for (int i = 0; i < doc.Pages.Count; i++)
{
    string headerText = "HEADER TEXT";
    PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 15f));
    SizeF size = font.MeasureString(headerText);
    doc.Pages[i].Canvas.DrawString(headerText, font, PdfBrushes.RoyalBlue, doc.Pages[i].Size.Width - 90 - size.Width, 35);
}

Step 4: Save to file.

doc.SaveToFile("output.pdf");

Output:

Add Header to Existing PDF in C#, VB.NET

Full Code:

[C#]
PdfDocument doc = new PdfDocument();
doc.LoadFromFile("sample.pdf");

for (int i = 0; i < doc.Pages.Count; i++)
{
    PdfImage headerImage = PdfImage.FromFile("logo.png");
    float width = headerImage.Width / 3;
    float height = headerImage.Height / 3;
    doc.Pages[i].Canvas.DrawImage(headerImage, 85, 20, width, height);

    string headerText = "HEADER TEXT";
    PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 15f));
    SizeF size = font.MeasureString(headerText);
    doc.Pages[i].Canvas.DrawString(headerText, font, PdfBrushes.RoyalBlue, doc.Pages[i].Size.Width - 90 - size.Width, 35);
}

doc.SaveToFile("output.pdf");
[VB.NET]
Dim doc As PdfDocument =  New PdfDocument() 
doc.LoadFromFile("sample.pdf")

Dim i As Integer
For  i = 0 To  doc.Pages.Count- 1  Step  i + 1
    Dim headerImage As PdfImage =  PdfImage.FromFile("logo.png") 
    Dim width As single =  headerImage.Width / 3 
    Dim height As single =  headerImage.Height / 3 
    doc.Pages(i).Canvas.DrawImage(headerImage, 85, 20, width, height)

    Dim headerText As String =  "HEADER TEXT" 
    Dim font As PdfTrueTypeFont =  New PdfTrueTypeFont(New Font("Impact",15f)) 
    Dim size As SizeF =  font.MeasureString(headerText) 
    doc.Pages(i).Canvas.DrawString(headerText, font, PdfBrushes.RoyalBlue, doc.Pages(i).Size.Width - 90 - size.Width, 35)
Next

doc.SaveToFile("output.pdf")