LoginSignup
21

More than 5 years have passed since last update.

PDFにページ番号を追加

Last updated at Posted at 2017-02-01

これなに

Python を使って、無料で PDF を編集する方法 を紹介します。
サンプルとして、各ページにページ番号を追加してみます。

image

インストール

下記を使用します。

  • ReportLab: Python用、PDF生成ライブラリ。有料版と無料版がある。
  • PyPDF2: Page単位のPDF編集ライブラリ。
  • PdfFormFiller: PDFにテキストを挿入するライブラリ。
インストール
conda install -y reportlab
pip install PyPDF2 pdfformfiller

Anaconda を使っていない場合は、conda の代わりに pip を使ってください。

ページ番号を追加するサンプル

日本語フォントとして、IPAexGothic フォントを使っていますが、別のフォントでも構いません。
(Ubuntu では、apt-get install fonts-ipaexfont でインストールできます)

注意点として、用紙サイズを表す PyPDF2.pdf.PageObject.mediaBox の要素である FloatObject が Decimalを返すため、実数との加減演算でエラーになります。ここでは、無理やり、FloatObject が実数と加減演算できるように置き換えています。

addPage(入力ファイル, 出力ファイル) とすると、元のPDFに、ページ番号を追加したPDFを作成できます。

python
import PyPDF2
class FloatObject(PyPDF2.generic.FloatObject):
    def __add__(self, other):
        return self.as_numeric() + other
    def __radd__(self, other):
        return self.as_numeric() + other
    def __sub__(self, other):
        return self.as_numeric() - other
    def __rsub__(self, other):
        return -self.as_numeric() + other
PyPDF2.generic.FloatObject = FloatObject

from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_CENTER
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from pdfformfiller import PdfFormFiller

def addPage(infile, outfile):
    # Linuxでは、'/usr/share/fonts/opentype/ipaexfont-gothic/ipaexg.ttf'など
    pdfmetrics.registerFont(TTFont('IPAexGothic', 'c:/Windows/Fonts/ipaexg.ttf'))
    sty = ParagraphStyle('sty', alignment=TA_CENTER, fontName='IPAexGothic', fontSize=9)
    ff = PdfFormFiller(infile)
    for i in range(ff.pdf.getNumPages()):
        p = ff.pdf.getPage(i)
        ff.add_text('ページ %d'%(i+1), i, (0,p.mediaBox[3]-30), p.mediaBox.getUpperRight(), sty)
    ff.write(outfile)
  • Windows, Ubuntu, Alpine-Linux で稼働確認しています。

追記

パッケージ化しました。

以上

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
21