Rotate all pages in an existing PDF document by 90 degrees clockwise using iTextSharp (v5 legacy).
/// <summary>
/// Rotate all pages in an existing PDF document by 90 degrees clockwise.
/// The original PDF <paramref name="source"/> file will be overwritten.
/// </summary>
/// <param name="source">PDF source file path.</param>
/// <remarks>
/// Rotate a page 90 degrees in iText 5-legacy:
/// https://itextpdf.com/en/resources/examples/itext-5-legacy/scaling-and-rotating-pages
/// </remarks>
public static void RotateRight(string source)
{
using (var reader = new PdfReader(new FileStream(source, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)))
{
var numberOfPages = reader.NumberOfPages;
for (var p = 1; p <= numberOfPages; p++)
{
var page = reader.GetPageN(p);
var rotate = page.GetAsNumber(PdfName.ROTATE);
if (rotate == null)
{
page.Put(PdfName.ROTATE, new PdfNumber(90));
}
else
{
page.Put(PdfName.ROTATE, new PdfNumber((rotate.IntValue + 90) % 360));
}
}
var pdfStamper = new PdfStamper(reader, new FileStream(source, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite));
pdfStamper.Close();
reader.Close();
}
}