Rotate PDF files in Python

While working with PDF files programmatically, you may need to rotate the pages in a PDF. This is required to change the orientation of the PDF pages from portrait to landscape or vice versa. To accomplish that, this article provides you with the easiest solution of how to rotate PDF files in Python. The step-by-step guide and code sample will demonstrate how to switch the orientation of the pages in a PDF file.

Python Library to Rotate PDF Files

To rotate PDF files, we will use Aspose.PDF for Python. It is a powerful library to seamlessly create, process, and convert PDF files. You can use the following pip command to install the library from PyPI.

pip install aspose-pdf

Rotate a PDF File in Python

You can rotate the pages in a PDF and change their orientation to landscape or portrait. In both cases, you only need to swap the values of page’s height and width and set the angle at which the content of the page will be rotated. This will automatically change the orientation from portrait to landscape and landscape to portrait.

The following are the steps to rotate a PDF file in Python.

  • First, create an instance of the Document class and initialize it with the input PDF file’s path.
  • Then, start a loop to access each page of the PDF using Document.pages collection.
  • In each iteration, update the height and width of the page and set rotation angle.
  • Finally, call Document.save() method to save the updated PDF file.

The following code sample shows how to rotate the pages in a PDF in Python.

The above code sample rotates all the pages in the PDF file. However, you can modify it to rotate a single page or certain pages only. In addition, we have rotated each page’s content to 90 degrees. You can also use other angles available in aspose.pdf.Rotation enum. The other values of aspose.pdf.Rotation enum include ON180, ON270, and NONE.

Online Tool to Rotate PDF Files

If you want to rotate PDF files online, you can use our free tool, which is developed using Aspose.PDF library.

Get a Free License

We provide a free temporary license that you can use to evaluate the PDF rotation feature without any limitations.

Explore Python PDF Library

You can learn more about our Python PDF library using the documentation. Explore the features of the library and let us know about your feedback or queries via our forum.

Conclusion

In this article, you have learned how to rotate PDF files in Python. The step-by-step guide and code sample have demonstrated how to change the orientation of PDF pages from portrait to landscape or landscape to portrait. You can easily install the library and implement the PDF rotation feature in your application.

See Also