Showing posts with label Rotate. Show all posts
Showing posts with label Rotate. Show all posts

Monday, April 22, 2019

C# - Pdf rotate using iTextSharp

In C#, with opensource iTextSharp can be find in nuget package, we can easily rotate each pdf pages and save as new file, use below code

using iTextSharp.text;
using iTextSharp.text.pdf;

using System.IO;


namespace PdfRotate
{
    class Program
    {
        static void Main(string[] args)
        {
            //INFO: Change input and ouput path here
            string pdfFilePath = @"C:\Files\sample.pdf";
            string outputPath = @" C:\Files\sampleoutput.pdf ";

            //INFO: Change rotate degree here to 90, 180 etc
            RotatePages(pdfFilePath, outputPath, 180);           
        }

        private static void RotatePages(string pdfFilePath, string outputPath, int rotateDegree)
        {
            PdfReader reader = new PdfReader(pdfFilePath);
            int pagesCount = reader.NumberOfPages;

            for (int n = 1; n <= pagesCount; n++)
            {
                PdfDictionary page = reader.GetPageN(n);
                PdfNumber rotate = page.GetAsNumber(PdfName.ROTATE);
                int rotation =
                        rotate == null ? rotateDegree : (rotate.IntValue + rotateDegree) % 360;

                page.Put(PdfName.ROTATE, new PdfNumber(rotation));
            }

            PdfStamper stamper = new PdfStamper(reader, new FileStream(outputPath, FileMode.Create));
            stamper.Close();
            reader.Close();
        }
    }
}