0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでPDFを編集する:構造、内容、セキュリティ設定

Posted at

Pythonを使用してPDF文書を編集する

PDF形式は、そのレイアウトの安定性やプラットフォーム間での一貫性から、契約書、報告書、電子フォームなど幅広い用途で活用されています。一方で、「簡単には編集できない」という性質ゆえに、自動処理が難しいという課題もあります。

しかし、Pythonを活用すれば、PDFのページ操作、テキストや画像の差し替え、フォーム処理、権限設定などを効率的に実現でき、文書の自動アーカイブ、システム出力、データ処理など様々な場面で役立ちます。

本記事では、PythonでPDF文書を編集する方法を紹介し、PDFの精密な操作やバッチ処理を可能にするテクニックを解説します。

本記事の内容:

  • PythonでPDFを読み込む
  • ページの挿入・削除
  • PDF内のテキストを置換する
  • PDF内の画像を置換する
  • PDFフォームへの入力・読み取り
  • PDFのパスワード・アクセス権限の設定
  • PDFのメタデータおよびビューア設定の編集

ここで紹介する操作は、Free Spire.PDF for Python を使用して行います。インストールは以下のコマンドで可能です:

pip install spire.pdf.free

PythonでPDFを読み込む

PdfDocument クラスを初期化し、LoadFromFile でファイルパスから、または LoadFromStream でバイトストリームからPDFを読み込みます。

# PDFドキュメントを作成
pdf = PdfDocument()

# ファイルからPDFを読み込む
pdf.LoadFromFile("sample.pdf")

# バイトストリームからPDFを読み込む
with open("sample.pdf", "rb") as f:
    byte_data = f.read()

pdfStream = Stream(byte_data)
pdf = PdfDocument(pdfStream)

用途に応じて、いずれかの読み込み方法を選びましょう。


ページの挿入・削除

PDFのページ構造は Pages コレクションを通じて動的に編集できます。空白ページの挿入や、不要なページの削除が可能です。

操作手順:

  • PdfDocument.LoadFromFile() で既存のPDFを読み込む
  • Pages.Insert() でページを挿入
  • Pages.RemoveAt() でページを削除
  • SaveToFile()Close() で保存および終了
from spire.pdf import PdfDocument, PdfPageSize, PdfMargins, PdfPageRotateAngle

pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")

# 1ページ目を挿入(90度回転)
pdf.Pages.Insert(0, PdfPageSize.A4(), PdfMargins(50, 60), PdfPageRotateAngle.RotateAngle90)

# 2ページ目を削除
pdf.Pages.RemoveAt(1)

pdf.SaveToFile("output/InsertDeletePage.pdf")
pdf.Close()

PDF内のテキストを置換する

PdfTextReplacer を使用すれば、PDF内の特定の文字列を検索・置換できます。テンプレートの自動入力やテキスト修正に便利です。

操作手順:

  • PdfTextReplacer() で置換オブジェクトを作成
  • ReplaceActionType.IgnoreCase などの一致オプションを設定
  • ReplaceAllText() で対象の文字列を一括置換
from spire.pdf import PdfDocument, PdfTextReplacer, ReplaceActionType, Color

pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")

for i in range(pdf.Pages.Count):
    page = pdf.Pages.get_Item(i)
    replacer = PdfTextReplacer(page)
    replacer.Options.ReplaceType = ReplaceActionType.IgnoreCase
    replacer.ReplaceAllText("drones", "ROBOTS", Color.get_Aqua())

pdf.SaveToFile("output/ReplaceText.pdf")
pdf.Close()

PDF内の画像を置換する

PdfImageHelper を使うことで、埋め込み画像の取得・置換が可能です。ロゴの変更や画像の一括更新などに最適です。

操作手順:

  • GetImagesInfo() で画像情報を取得
  • PdfImage.FromFile() で新しい画像を読み込み
  • ReplaceImage() で対象画像を差し替え
from spire.pdf import PdfDocument, PdfImageHelper, PdfImage

pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")

page = pdf.Pages.get_Item(0)
image_info = PdfImageHelper().GetImagesInfo(page)[0]
new_image = PdfImage.FromFile("Image.png")
PdfImageHelper().ReplaceImage(image_info, new_image)

pdf.SaveToFile("output/ReplaceImage.pdf")
pdf.Close()

PDFフォームへの入力・読み取り

Spire.PDFを使用すると、PDFフォームの各フィールドにアクセスして、自動入力や値の抽出が行えます。

操作手順:

  • PdfFormWidget でフォームを取得
  • FieldsWidget を使って全フィールドにアクセス
  • フィールドタイプに応じて値を設定または取得
from spire.pdf import PdfDocument, PdfFormWidget, PdfTextBoxFieldWidget

pdf = PdfDocument()
pdf.LoadFromFile("EmployeeInformationForm.pdf")
form_widgets = PdfFormWidget(pdf.Form).FieldsWidget

# フォーム入力
for field in form_widgets:
    if field.Name == "FullName":
        PdfTextBoxFieldWidget(field).Text = "Amanda Ray Thompson"

# フィールド値の取得
form_values = []
for field in form_widgets:
    if isinstance(field, PdfTextBoxFieldWidget):
        form_values.append(f"{field.Name}: {field.Text}")

with open("output/FormValues.txt", "w") as f:
    f.write("\n".join(form_values))

pdf.SaveToFile("output/FilledForm.pdf")
pdf.Close()

PDFのパスワードとアクセス権限を設定する

Spire.PDFを使えば、ドキュメントの暗号化や、印刷・コピーなどの操作制限が可能です。機密情報の保護に最適です。

操作手順:

  • PdfPasswordSecurityPolicy() を使ってパスワードを設定
  • PdfEncryptionAlgorithm.AES_128 などの暗号方式を指定
  • PdfDocumentPrivilege で許可項目を定義
  • Encrypt() で暗号化を適用
from spire.pdf import PdfDocument, PdfPasswordSecurityPolicy, PdfEncryptionAlgorithm, PdfDocumentPrivilege

pdf = PdfDocument()
pdf.LoadFromFile("EmployeeInformationForm.pdf")

policy = PdfPasswordSecurityPolicy("userPSD", "ownerPSD")
policy.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES_128

privilege = PdfDocumentPrivilege.ForbidAll()
privilege.AllowPrint = True
privilege.AllowFillFormFields = True
policy.DocumentPrivilege = privilege

pdf.Encrypt(policy)
pdf.SaveToFile("output/EncryptedForm.pdf")
pdf.Close()

PDFのメタデータとビューア設定を編集する

PDFのプロパティや表示設定を編集することで、文書の管理効率や読みやすさを向上させることができます。

操作手順:

  • DocumentInformation でタイトルや作成者を設定
  • ViewerPreferences でツールバーの非表示やレイアウトを調整
  • 保存して完了
from spire.pdf import PdfDocument, PdfPageLayout, PrintScalingMode

pdf = PdfDocument()
pdf.LoadFromFile("EmployeeInformationForm.pdf")

# メタデータの設定
pdf.DocumentInformation.Author = "John Doe"
pdf.DocumentInformation.Title = "Employee Information Form"

# ビューア設定の変更
prefs = pdf.ViewerPreferences
prefs.DisplayTitle = True
prefs.HideToolbar = True
prefs.PageLayout = PdfPageLayout.OneColumn

pdf.SaveToFile("output/EditViewerPreference.pdf")
pdf.Close()

まとめ

Pythonを使えば、少ないコード量でPDFの様々な編集作業を自動化できます:

  • ページ構造の調整:ページの挿入・削除
  • コンテンツの編集:テキストや画像の置換
  • フォーム操作:フィールドの入力・取得
  • セキュリティの管理:パスワードや権限設定
  • メタ情報の調整:作成者、表示設定の変更

これらの機能は、テンプレート処理、自動アーカイブ、電子フォーム生成などの場面で活用でき、軽量なドキュメントシステムの構築に非常に有用です。


📚 詳しい使い方は:Spire.PDF for Python チュートリアルセンター をご覧ください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?