-
Notifications
You must be signed in to change notification settings - Fork 678
Description
Hello, I am building a resize_pdf_pages function in python, and I have reliably been able to get the desired output, which is standardizing pages to 8.5" X 11" format. Page.show_pdf_page() made this very easy, but I am losing all annotations in the process, as this method does not preserve them. How do I both resize the pages and preserve the annotations?
I want the input and output documents to be "the same", other than resizing where needed. In the event of a page being too large, I would like the annotations to scale down with the original page, keeping their relative position to the input page. In the event of a page being too small, I do not scale the page up at all, I post it to the center of a standard 8.5" x 11" page. I would like to preserve the annotation positions relative to the original page size in this case.
Here is my current function:
def resize_pdf_pages(file_field, output_width=612, output_height=792):
file_bytes = file_field.read()
output_doc = fitz.open()
with fitz.open("pdf", file_bytes) as pdf:
for page_number in range(pdf.page_count):
page = pdf.load_page(page_number)
width = page.mediabox[2]
height = page.mediabox[3]
new_page = output_doc.new_page(width=output_width, height=output_height)
if width == output_width and height == output_height:
# Page dimensions already match the output size, copy the page
new_page.show_pdf_page(new_page.rect, pdf, page_number)
else:
# Page needs resizing or center-justification
if width <= output_width and height <= output_height:
# Page is smaller than the output size, center-justify the image
new_page.show_pdf_page(
fitz.Rect(
(output_width - width) / 2,
(output_height - height) / 2,
(width + output_width) / 2,
(height + output_height) / 2
),
pdf, page_number, keep_proportion=True
)
else:
# Page is larger than the output size, resize and center-justify the image
new_page.show_pdf_page(
new_page.rect,
pdf, page_number, keep_proportion=True
)
return BytesIO(output_doc.write())