42 lines
1.4 KiB
Python
42 lines
1.4 KiB
Python
from PyPDF2 import PdfReader, PdfWriter
|
|
|
|
# A4 dimensions in points (1mm = 2.83465 points)
|
|
A4_WIDTH = 210 * 2.83465 # ≈ 595.276 pts (width)
|
|
A4_HEIGHT = 297 * 2.83465 # ≈ 841.89 pts (height)
|
|
|
|
def fit_to_a4(input_pdf_path, output_pdf_path):
|
|
reader = PdfReader(input_pdf_path)
|
|
writer = PdfWriter()
|
|
|
|
for page in reader.pages:
|
|
# Get original page dimensions
|
|
orig_width = float(page.mediabox.width)
|
|
orig_height = float(page.mediabox.height)
|
|
|
|
# Calculate scaling factor to fit A4 (preserve aspect ratio)
|
|
scale = min(A4_WIDTH / orig_width, A4_HEIGHT / orig_height)
|
|
|
|
# Scale the page content
|
|
page.scale_by(scale)
|
|
|
|
# Calculate offsets to center on A4
|
|
new_width = orig_width * scale
|
|
new_height = orig_height * scale
|
|
x_offset = (A4_WIDTH - new_width) / 2
|
|
y_offset = (A4_HEIGHT - new_height) / 2
|
|
|
|
# Set A4 mediabox and shift content
|
|
page.mediabox.lower_left = (x_offset, y_offset)
|
|
page.mediabox.upper_right = (x_offset + new_width, y_offset + new_height)
|
|
|
|
writer.add_page(page)
|
|
|
|
# Save the output PDF
|
|
with open(output_pdf_path, "wb") as out_file:
|
|
writer.write(out_file)
|
|
|
|
|
|
|
|
# Example usage
|
|
fit_to_a4(r"z:\Dropbox\Ordinace\Dokumentace_ke_zpracování\untitled.pdf", r"z:\Dropbox\Ordinace\Dokumentace_ke_zpracování\output_a4.pdf")
|
|
print("PDF adjusted to A4 portrait successfully!") |