PyPDF2の使い方

投稿者: | 2018年8月18日

PyPDF2とは、pythonでPDFを扱うためのモジュールです。PDFの生成(特に日本語を含む場合)は苦手ですが、ページの抽出、結合、回転などは他のモジュールではできないため、PyPDF2を使用します。

PDFの結合

PDF1の後にPDF2を結合する場合のサンプルコードです。

# -*- coding: utf-8 -*-

#結合するPDFを記入。PDF1の後ににPDF2を結合し、OutputNameで書き出す
PDF1 = ‘D:\\aaa.pdf’
PDF2 = ‘D:\\bbb.pdf’
OutputName = ‘D:\\ccc.pdf’

import PyPDF2

File1 = open(PDF1, ‘rb’)
File2 = open(PDF2, ‘rb’)
Reader1 = PyPDF2.PdfFileReader(File1)
Reader2 = PyPDF2.PdfFileReader(File2)
Writer = PyPDF2.PdfFileWriter()

for page in range(Reader1.numPages):
Obj = Reader1.getPage(page)
Writer.addPage(Obj)

for page in range(Reader2.numPages):
Obj = Reader2.getPage(page)
Writer.addPage(Obj)

OutputFile = open(OutputName, ‘wb’)
Writer.write(OutputFile)
OutputFile.close()
File1.close()
File2.close()

 

ページの抽出

複数のページを持つPDFから任意のページのみを抽出するサンプルコードです。先頭ページは「0」として数えます。

# -*- coding: utf-8 -*-

#ページを抽出する
PDF = ‘D:\\aaa.pdf’ #入力ファイル名
OutputName = ‘D:\\ccc.pdf’ #出力ファイル名
Page = 2 #抽出するページ(先頭を0として数える)

import PyPDF2

File = open(PDF, ‘rb’)
Reader = PyPDF2.PdfFileReader(File)
Writer = PyPDF2.PdfFileWriter()

obj = Reader.getPage(Page)
Writer.addPage(obj)

Output = open(OutputName, ‘wb’)
Writer.write(Output)
Output.close()
File.close()

 

ページの回転

すべてのページを時計回りに回転させます。角度は、90°、180°、270°を選択できます。

# -*- coding: utf-8 -*-

#すべてのページを時計回りに回転させる
PDF = ‘D:\\aaa.pdf’ #入力ファイル名
OutputName = ‘D:\\ccc.pdf’ #出力ファイル名
angle = 270 #回転角度

import PyPDF2

File = open(PDF, ‘rb’)
Reader = PyPDF2.PdfFileReader(File)
Writer = PyPDF2.PdfFileWriter()
for page in range(Reader.numPages):
obj = Reader.getPage(page)
obj.rotateClockwise(angle)
Writer.addPage(obj)

Output = open(OutputName, ‘wb’)
Writer.write(Output)
Output.close()
File.close()

 

ページ作成などは別のモジュール、もしくはMicrosoft Officeなどを使用する必要がありますが、スキャナで取り込んだPDFなどの編集にはPyPDF2が便利です。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です