Crop PDF pages in Python

If you are dealing with PDF files, you may often need to trim the size of the pages programmatically. For example, you may want to crop the white margins around the content of the PDF pages. So in this article, you will learn how to crop PDF pages in Python. The guidelines and code sample will demonstrate each step from loading the PDF to saving its updated version after cropping.

Python Library to Crop PDF Pages

To crop PDF files, we will use Aspose.PDF for Python. The library provides a complete set of features to create and manipulate PDF files from within the Python applications. You can use the following pip command to install the library from PyPI.

pip install aspose-pdf

Crop a PDF Page in Python

The following are the steps to crop pages in a PDF file using our Python PDF library. For demonstration, we will crop only the first page of the PDF. However, you can modify the code to crop all or specific pages only.

  • First, use Document class to load the input PDF file using its path.
  • Then, create a new Rectangle and initialize it with the size that you will use to crop the page.
  • Use Document.pages collection to select the desired page and assign Rectangle object to crop_box, trim_box, art_box, and bleed_box properties.
  • Finally, call Document.save() method to save the updated PDF file.

The following code sample shows how to crop a PDF page in Python.

Online Tool to Crop PDF Files

We also have a free online tool to crop PDF files in just a few clicks. If you need to crop your PDF or want to evaluate the PDF cropping feature, you can use it without signing up.

Get a Free License

You can get a free temporary license and evaluate the PDF cropping feature without any limitations.

Explore Python PDF Library

Visit the documentation of our Python PDF library to explore its amazing features. In case you would have any suggestions, questions, or queries, let us know via our forum.

Conclusion

In this article, you have learned how to crop PDF pages in Python. Following the guidelines and code sample provided above, you can easily perform PDF cropping in your application. Simply install Aspose.PDF for Python and enjoy its powerful PDF manipulation features.

See Also