LoginSignup
0
2

More than 1 year has passed since last update.

[Python]2ページ両面印刷用にPDFを変換

Last updated at Posted at 2021-09-11

目的

自宅のプリンタの両面印刷機能がA4でないと使えないため、下記のように変換
変換前: [0, 1, 2, 3, ...]
変換後: [[0,2], [1,3], ...]
印刷後に裁断し、A5冊子化する

環境

  • VSCode
  • Ubuntu 20.04 LTS(WSL)

使用ライブラリ

pip install PyPDF2

コード

pdf_converter.py
import sys
import os
import PyPDF2 as pdf

def main(args):
    file_path = args[1]
    if not os.path.exists(file_path):
        print("Invalid args: No exists file_path")
        sys.exit(-1)
    f = open(file_path, 'rb')
    reader = pdf.PdfFileReader(f)

    page_num = reader.getNumPages()
    media = reader.getPage(0).mediaBox
    page_w = media.upperRight[0]
    page_h = media.upperRight[1]
    print(page_num)
    print(page_w)
    print(page_h)

    writer = pdf.PdfFileWriter()

    for i in range(0, page_num, 4):
        #print(i)
        cnt = 4
        if page_num-i < 4:
            cnt = page_num-i
        page02 = pdf.pdf.PageObject.createBlankPage(width=page_w*2, height=page_h)
        page13 = pdf.pdf.PageObject.createBlankPage(width=page_w*2, height=page_h)

        for j in range(cnt):
            if j==0 or j==3:    #上
                x = 0
            else:               #下
                x = page_w

            if j%2 == 0:    #奇数ページ
                page02.mergeTranslatedPage(reader.getPage(i+j), x, 0, expand=False)
            else:           #偶数ページ
                page13.mergeTranslatedPage(reader.getPage(i+j), x, 0, expand=False)

        # 回転
        page02.rotateClockwise(90)
        page13.rotateCounterClockwise(90)

        # ページ追加
        writer.addPage(page02)
        writer.addPage(page13)

    output_path = "./out.pdf"
    output_file = open(output_path, 'wb')
    writer.write(output_file)
    output_file.close()
    f.close()


if __name__ == "__main__":
    args = sys.argv
    main(args)

結果

$ python3 pdf_converter.py sample.pdf
  • 変換前 sample.PNG
  • 変換後 result.PNG

MEMO

PyPDF2.mergeScaledTranslatedPageを使用するつもりだったが、回転と平行移動を共に行った際の挙動が思ったものと違った為、連結後に回転処理を実行

参考ページ

0
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
0
2