Created
December 21, 2022 15:35
-
-
Save EtaoinWu/f7b665132a90ce5ac46ff2c5313ab880 to your computer and use it in GitHub Desktop.
Merge PDFs into one and rescale them all to A4 width (21cm or 595px)
This file contains 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
from PIL import Image | |
from PyPDF2 import PdfWriter, PdfReader | |
import tempfile | |
PREPEND_FILE = "打分框.pdf" | |
def scale_pdf_to_a4(input): | |
reader = input | |
if not isinstance(input, PdfReader): | |
reader = PdfReader(input) | |
for page in reader.pages: | |
scale = 595.0 / float(page.mediabox.width) | |
page.scale_by(scale) | |
return reader | |
def merge_files_into_pdf(fs, output): | |
merger = PdfWriter() | |
def append(x): | |
if isinstance(x, str): | |
x = PdfReader(x) | |
x = scale_pdf_to_a4(x) | |
for page in x.pages: | |
merger.add_page(page) | |
append(PREPEND_FILE) | |
for f in fs: | |
if f.endswith(".pdf"): | |
append(f) | |
elif ( | |
f.endswith(".png") | |
or f.endswith(".jpg") | |
or f.endswith(".jpeg") | |
or f.endswith(".jfif") | |
or f.endswith(".pjpeg") | |
or f.endswith(".pjp") | |
or f.endswith(".svg") | |
or f.endswith(".gif") | |
or f.endswith(".webp") | |
or f.endswith(".bmp") | |
or f.endswith(".ico") | |
or f.endswith(".tif") | |
or f.endswith(".tiff") | |
): | |
# create a temporary file | |
temp = tempfile.NamedTemporaryFile(suffix=".pdf") | |
# convert image into pdf and save it to temp | |
img = Image.open(f) | |
width, height = img.size | |
desired_resolution = 418 / 3456 * width | |
img.save(temp, "PDF", resolution=desired_resolution, save_all=True) | |
# read temp and append it to merger | |
temp.seek(0) | |
append(temp) | |
merger.write(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment