Skip to content

Instantly share code, notes, and snippets.

@flandersen
Created July 21, 2023 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flandersen/97f28471a18d16f952fafec129cbfcb4 to your computer and use it in GitHub Desktop.
Save flandersen/97f28471a18d16f952fafec129cbfcb4 to your computer and use it in GitHub Desktop.
Adding printing margin to PDF files
#!/usr/bin/env python
"""
Adds a printing margin to pdf files by scaling down the content and moving it to the center.
Scale factor must be adapted to the needs.
Usage: pdfmargin.py file1.pdf file2.pdf ...
"""
import os
import sys
from decimal import Decimal
from PyPDF2 import PageObject, PdfReader, PdfWriter, Transformation
__author__ = "Flandersen"
__copyright__ = "Copyright 2023"
scale = 0.95
for input_file in sys.argv[1:]:
file_without_ext = os.path.splitext(input_file)[0]
output_file = "{0}_margin.pdf".format(file_without_ext)
pdf = PdfReader(input_file)
writer = PdfWriter()
for page in pdf.pages:
original_width = page.artbox.width
original_height = page.artbox.height
op = Transformation().scale(sx=scale, sy=scale)
page.add_transformation(op)
new_width = original_width * Decimal(scale)
new_height = original_height * Decimal(scale)
tx = (original_width - new_width) / Decimal(2.0)
ty = (original_height - new_height) / Decimal(2.0)
op = Transformation().translate(tx, ty)
page.add_transformation(op)
new_page = PageObject.create_blank_page(pdf, original_width, original_height)
new_page.merge_page(page)
writer.add_page(new_page)
with open(output_file, "wb+") as f:
writer.write(f)
# EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment