3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python: PDFファイル内の全ページを任意のサイズに変換する

Posted at
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読み書きは割愛。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?