from enum import Enum
from io import BytesIO
import PyPDF2
class PDFSizeParam(tuple, Enum):
PX_72DPI_A4 = (595, 847)
PX_300DPI_A4 = (2480, 3508)
PX_350DPI_A4 = (2894, 4093)
def scale_pdf_to(pdf_bytes: bytes, scale_to: PDFSizeParam = PDFSizeParam.PX_72DPI_A4) -> bytes:
reader = PyPDF2.PdfFileReader(BytesIO(pdf_bytes))
num_pages = reader.getNumPages()
pages = [reader.getPage(i) for i in range(num_pages)]
[page.scaleTo(scale_to.value[0], scale_to.value[1]) for page in pages]
writer: PyPDF2.PdfFileWriter = PyPDF2.PdfFileWriter()
[writer.addPage(page) for page in pages]
temp_pdf: BytesIO = BytesIO()
writer.write(temp_pdf)
temp_pdf.seek(0)
return temp_pdf.read()
bytes <-> File読み書きは割愛。