Python を使用して PDF から添付ファイルを抽出します

Python を使用してPDFから添付ファイルをプログラムで抽出する方法

Python for .NET ライブラリを使用して添付ファイルを抽出する方法

添付ファイルをPDFファイルに抽出するために、python-net プラットフォーム用の機能豊富で強力で使いやすいドキュメント操作APIである Aspose.PDF for .NET APIを使用します。NuGet パッケージマネージャーを開き、aspose.pdf を検索してインストールします。パッケージマネージャーコンソールから次のコマンドを使用することもできます。

Console

pip install aspose-pdf

PDF Python から添付ファイルを抽出


ご使用の環境でコードを試すには Aspose.PDF for .NET が必要です。

  1. 埋め込みファイルコレクションを取得します。
  2. 埋め込みファイルの数を取得します。
  3. コレクションをループして、すべての添付ファイルを取得します。
  4. パラメーターオブジェクトにパラメーターが含まれているかどうかを確認します。
  5. 添付ファイルを取得し、ファイルまたはストリームに書き込みます。

PDF ドキュメントから添付ファイルを抽出

import aspose.pdf as apdf

from os import path

path_infile = path.join(self.data_dir, infile)
# Open document
document = apdf.Document(path_infile)

# Get count of the embedded files
print(f"Total files : {len(document.embedded_files)}")

# Loop through the collection to get all the attachments
for file_specification in document.embedded_files:
    print(f"Name: {file_specification.name}")
    print(f"Description: {file_specification.description}")
    print(f"Mime Type: {file_specification.mime_type}")

    # Check if parameter object contains the parameters
    if file_specification.params is not None:
        print(f"CheckSum: {file_specification.params.check_sum}")
        print(f"Creation Date: {file_specification.params.creation_date}")
        print(f"Modification Date: {file_specification.params.mod_date}")
        print(f"Size: {file_specification.params.size}")

    # Get the attachment and write to file
    with open(
        path.join(self.data_dir, "export_" + file_specification.name), "wb"
    ) as f:
        f.write(file_specification.contents.readall())