How to Rotate PDF using Python

This brief guide explains how to rotate PDF using Python. It contains the detailed steps for writing the software and shares a sample code to demonstrate the process to rotate PDF file using Python. You will learn the process to change the page orientation from portrait to landscape and vice versa along with the options to rotate the page contents also if required.

Steps to Change PDF Orientation using Python

  1. Set the development environment to use Aspose.PDF for Python via .NET to rotate pages
  2. Load the source PDF file using the Document class whose contents and page orientation are to be changed
  3. Parse through each page of the PDF file and interchange height with width to change the orientation
  4. Rotate the page contents also if required
  5. Save the output PDF file on the disk with modified orientation and rotated contents

These steps encompass the complete process to rotate PDF permanently using Python. In the beginning, the source PDF file is loaded and each page is parsed where first the height and width of the page are interchanged thus changing its orientation however with this step only the page dimensions are changed but the orientation of the content remains the same. If you want to rotate the contents also, you may set the Page.rotate value with one of the values from the aspose.pdf.Rotation enumerator.

Code to Rotate PDF using Python

The aforementioned code demonstrates the operation to rotate all pages in PDF using Python. The media_box properties are used to calculate new dimensions of the target page like source height is set as destination width and source width is set as destination height. If you want to rotate the page contents also, you may use aspose.pdf.Rotation enumerator that contains values like ON90, ON180, ON270, and NONE for setting the value of Page.rotate property.

This article has guided us to rotate PDF page and contents. If you want to render text on a PDF page at any location at a random angle refer to the article on how to rotate text in PDF using Python.

 English