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

PyPDF2のチートシート

Posted at

PyPDF2のチートシートです。あんま需要ないかな…(小声)

#####ディレクトリ内のPDFファイルをすべて結合

import PyPDF2
import glob #特定のディレクトリ(ファイル)を処理
import os

def merge_pdf(dir_path, dst_path):
    dir = glob.glob(os.path.join(dir_path, '*.pdf'))
    dir.sort() #昇順に並び替え

    merger = PyPDF2.PdfFileMerger()
    for i in dir:
      if not PyPDF2.PdfFileReader(p).isEncrypted: #暗号化されたファイル除外
            merger.append(i)

    merger.write(dst_path) #PDFファイルを書き出し
    merger.close()

merge_pdf('d/pdf', 'd/sample.pdf')

#####指定して結合

import PyPDF2

merger = PyPDF2.PdfFileMerger()

merger.append('data/src/pdf/sample1.pdf') #Sample1
merger.append('data/src/pdf/sample2.pdf') #Sample2

merger.write('d/sample.pdf') #Sample1+2
merger.close()

#####分割 (※分割用のメソッドはないのでページ指定して新規保存)

import PyPDF2

merger = PyPDF2.PdfFileMerger()

# まず、2ページ目までを保存
merger.append('d/sample1.pdf', pages=PyPDF2.pagerange.PageRange(':2'))

merger.write('d/sample_split1.pdf')
merger.close()

merger = PyPDF2.PdfFileMerger()

# 次に、2ページからを保存
merger.append('data/src/pdf/sample1.pdf', pages=PyPDF2.pagerange.PageRange('2:'))

merger.write('d/sample_split2.pdf')
merger.close()
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?