How to Rotate PDF using C#

This article assists with how to rotate PDF using C#. It explains the resources required to set the IDE configurations, a list of tasks to be performed to achieve the required results, and a runnable sample code to change PDF orientation using C#. The sample code can be executed in any of the environments supporting .NET and does not require any other third-party tool or software to rotate PDF permanently.

Steps to Rotate PDF File using C#

  1. Set the environment to add Aspose.PDF for .NET to rotate the pages
  2. Load the input PDF using the Document class for changing the orientation
  3. Parse through each page and get the rectangle area using the MediaBox property
  4. Interchange the MediaBox rectangle length with width in a temporary variable
  5. Set MediaBox and CropBox to the updated rectangle
  6. Set the Rotation property of the page to rotate contents also
  7. Save the resultant PDF file with a modified orientation for the page and contents

The aforementioned steps guide how to rotate pages in PDF using C#. In the beginning, the source PDF is loaded into the Document class object and then each page is parsed to access its MediaBox rectangle. The length and width of the rectangle are interchanged and then set back as new MediaBBox and CropBox of the page before saving the resultant PDF file on the disk.

Code to Rotate All Pages in PDF using C#

This code demonstrates how to rotate PDF file using C#. We can see that each page has MediaBox property that can be used to rotate the page such that the width of the MediaBox rectangle is exchanged with its height and a new rectangle is calculated thus changing the page orientation only whereas the contents are not changed. If you want to change the orientation of the content also, then use the Rotate property of the page that is set to Rotation.on270 in this sample code.

This article has guided us on rotating the page and contents of each page of a PDF file. If you want to learn the process to rearrange the pages in a PDF, refer to the article on how to rearrange pages in a PDF using C#.

 English