Created
February 15, 2026 10:34
-
-
Save s3rvac/a79b8734878935ca305d677e930ba792 to your computer and use it in GitHub Desktop.
A Python script for adding margins to PDF files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # | |
| # Adds margins to the given PDF file. | |
| # | |
| # Requirements: | |
| # | |
| # pip install pypdf | |
| # | |
| # Usage: | |
| # | |
| # python add_margins_to_pdf.py <input.pdf> | |
| # | |
| # It creates a file named `<input>-margins.pdf`. | |
| # | |
| # (Written with the help of Claude Sonnet 4.5.) | |
| # | |
| import pathlib | |
| import sys | |
| import pypdf | |
| margins_cm = 1.5 | |
| margins_pt = margins_cm * 28.35 | |
| reader = pypdf.PdfReader(sys.argv[1]) | |
| writer = pypdf.PdfWriter() | |
| # Clone the reader to preserve all the metadata and outline. | |
| writer.clone_document_from_reader(reader) | |
| # Modify each page except the first one, which usually contains the title | |
| # image. | |
| for page in writer.pages[1:]: | |
| # Get the original dimensions. | |
| original_width = float(page.mediabox.width) | |
| original_height = float(page.mediabox.height) | |
| # Create a new page with larger dimensions. | |
| new_width = original_width + 2 * margins_pt | |
| new_height = original_height + 2 * margins_pt | |
| # Translate the content to the center with the margins. | |
| page.add_transformation(pypdf.Transformation().translate(margins_pt, margins_pt)) | |
| # Set a new mediabox. | |
| page.mediabox.lower_left = (0, 0) | |
| page.mediabox.upper_right = (new_width, new_height) | |
| # Write the output file. | |
| out_pdf_name = pathlib.Path(sys.argv[1]).stem + "-margins.pdf" | |
| with open(out_pdf_name, "wb") as f: | |
| writer.write(f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment