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.

Revisions

  1. Aimeast created this gist Jan 26, 2022.
    52 changes: 52 additions & 0 deletions Program.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    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));
    }