Scale pdf to DINA4 and then add a 3mm black margin around it (python)

Question:

I have to check if a pdf file has the format of DIN-A4 and if it’s not it should be scaled to DIN-A4 (210mm x 297mm). After this on each side of the pdf should be added a 3mm black margin, so that the document has a width of 216mm and a height of 303mm in the end.

I don’t find any solutions for python.

I know how to crop a image, but not how to scale it up and especially not how to add a margin.

Asked By: Scamander 1920

||

Answers:

import fitz  # import PyMuPDF
src = fitz.open("input.pdf")  # input PDF
doc = fitz.open()  # the new output PDF
a4 = fitz.paper_rect("a4")
# 3 mm are about 8.5 points
border = 8.5
a4plus = a4 + (0, 0, 2*border, 2*border) # output page size
# A4 inside target rectangle
tar_rect = a4plus + (border, border, -border, -border)

#border position
bor_rect = a4plus + (border/2, border/2, -(border/2), -(border/2))

for page in src:
    npage = doc.new_page(width=a4plus.width, height=a4plus.height)
    # draw a white rectangle with a 3 mm border on output page
    npage.draw_rect(bor_rect, color=0, width=border)
    # insert source page re-scaled to A4 into it
    npage.show_pdf_page(tar_rect, src, page.number)
doc.save("output.pdf")
Answered By: Jorj McKie
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.