Skip to content

Instantly share code, notes, and snippets.

@Aimeast
Created January 26, 2022 16:03
Show Gist options
  • Save Aimeast/eabc40c32b55aedc023997cf288596df to your computer and use it in GitHub Desktop.
Save Aimeast/eabc40c32b55aedc023997cf288596df to your computer and use it in GitHub Desktop.
Add headers to PDF files with Spire.Pdf
using Spire.Pdf;
using Spire.Pdf.Graphics;
// Main call
static void AddHeader(PdfPageBase page, string left, string center, string right)
{
var state = page.Canvas.Save();
RotatePage(page);
AddHeaderWithRotatedPage(page, left, center, right);
page.Canvas.Restore(state);
}
static void RotatePage(PdfPageBase page)
{
var width = page.ActualSize.Width;
var height = page.ActualSize.Height;
switch (page.Rotation)
{
case PdfPageRotateAngle.RotateAngle0:
break;
case PdfPageRotateAngle.RotateAngle90:
page.Canvas.TranslateTransform(0, height);
page.Canvas.RotateTransform(360 - 90);
break;
case PdfPageRotateAngle.RotateAngle180:
page.Canvas.TranslateTransform(width, height);
page.Canvas.RotateTransform(360 - 180);
break;
case PdfPageRotateAngle.RotateAngle270:
page.Canvas.TranslateTransform(width, 0);
page.Canvas.RotateTransform(360 - 270);
break;
default:
break;
}
}
static void AddHeaderWithRotatedPage(PdfPageBase page, string left, string center, string right)
{
var width = page.Rotation == PdfPageRotateAngle.RotateAngle90 || page.Rotation == PdfPageRotateAngle.RotateAngle270
? page.ActualSize.Height
: page.ActualSize.Width;
var font = new PdfFont(PdfFontFamily.TimesRoman, 14f);
if (!string.IsNullOrEmpty(left))
page.Canvas.DrawString(left, font, PdfBrushes.Black, width / 2, 5, new PdfStringFormat(PdfTextAlignment.Left));
if (!string.IsNullOrEmpty(center))
page.Canvas.DrawString(center, font, PdfBrushes.Black, width / 2, 5, new PdfStringFormat(PdfTextAlignment.Center));
if (!string.IsNullOrEmpty(right))
page.Canvas.DrawString(right, font, PdfBrushes.Black, width - 50, 5, new PdfStringFormat(PdfTextAlignment.Right));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment