はじめに
Aspose.PDF FOSS for Python は Document クラスを中心に構成されており、pages、form、outlines、tagged_content、attachments を構造的かつドキュメントレベルの編集のエントリーポイントとして公開します。ページコンテンツの追加を超えて、このライブラリは PDF を完全で配布可能なアーティファクトにする操作をカバーします:構造化データを収集・公開するインタラクティブなフォームフィールド、ドキュメントレベルのファイル添付、テキスト作成のためのフォント検出と埋め込み、そしてナビゲーション用のブックマークツリーです。これらすべての領域では、AsposePdfException をルートとした単一の例外階層を通じてエラーが発生するため、呼び出し側はモジュールごとに例外タイプを推測せずにパッケージ固有の失敗を捕捉できます。
このガイドでは、ドキュメント管理インターフェースの扱い方を示します:AsposePdfException のサブクラスを捕捉して区別すること、Form と Field を使用して AcroForm フィールドを作成・読み取りすること、FileSpecification を通じて添付ファイルを埋め込み・復元すること、FontRepository と FontRegistry でフォントを解決すること、そして OutlineCollection と OutlineItem を用いてブックマークツリーを構築することです。各セクションは現在のパッケージに存在するクラスとメソッドのみを使用します。
Aspose.PDF FOSS for Python は Python パッケージであり、aspose-pdf-foss-for-python と呼ばれ、MIT ライセンスの下でリリースされ、Python 3.11 以降が必要です。トップレベルモジュール名は aspose_pdf です。コアパッケージは cryptography と asn1crypto のみへ依存します;オプションのエクストラでは Pillow ベースの画像デコード、Brotli ベースの WOFF2 フォントサポート、そして HarfBuzz ベースの複雑なテキストレイアウトが追加されます。
主な機能
AsposePdfException を使用した例外処理
Aspose.PDF FOSS for Python のパッケージ固有エラーはすべて AsposePdfException から派生します。ほとんどのドキュメント処理失敗はその PdfException サブクラスに分類され、さらにそれが PdfParseException(不正な入力)、PdfSecurityException(暗号化およびパスワード失敗、InvalidPasswordException を含む)、PdfValidationException(構造的またはコンプライアンス違反)の基底となります。より具体的なサブクラスの後で最後に AsposePdfException を捕捉することで、呼び出し側は不正なパスワードと破損したファイルとで異なる対応を取れ、なおかつパッケージが発生し得るその他すべての例外に対して単一のフォールバックを持つことができます。
from aspose_pdf import Document
from aspose_pdf.exceptions import (
AsposePdfException,
InvalidPasswordException,
PdfParseException,
)
def open_document(path, password=None):
try:
document = Document()
document.load_from(path, password=password)
return document
except InvalidPasswordException:
print(f"{path}: a correct password is required")
except PdfParseException as error:
print(f"{path}: not a valid PDF ({error})")
except AsposePdfException as error:
# Catches every other aspose_pdf-specific error not handled above.
print(f"{path}: PDF operation failed ({error})")
return None
インタラクティブ フォーム フィールド
Document.form は、ドキュメントの AcroForm フィールド上に Form ファサードを返します。Form.add_text_field()、add_checkbox()、および add_radio_group() は、ページとウィジェット矩形に結び付けられた新しいターミナルフィールドを作成し、各々が Field を返します。Field は name、value、field_type を公開し、既存のフィールドを名前で検査および更新できるようにし、Field.remove() はフィールドを完全に削除します。
from aspose_pdf import Document
with Document() as document:
page = document.pages.add()
document.form.add_text_field("customer_name", page, (72, 700, 300, 720))
document.form.add_checkbox("subscribe", page, (72, 670, 90, 688), on_value="Yes")
document.form.add_radio_group(
"plan",
page,
{"Basic": (72, 630, 90, 648), "Pro": (72, 600, 90, 618)},
value="Basic",
)
for field in document.form.fields:
print(field.name, field.field_type, field.value)
for field in document.form.fields:
if field.name == "customer_name":
field.value = "Jane Doe"
document.form.generate_appearances()
document.save("form.pdf")
埋め込みファイルと添付ファイル
Document.add_attachment はバイト列をドキュメントレベルのファイル添付として埋め込み、保存時に PDF の /Names /EmbeddedFiles 名前ツリーに書き込まれ、オプションで MIME タイプ、説明、作成/変更日を付加します。Document.embedded_files はすべての添付ファイルを型付き FileSpecification(name、contents、mime_type、description、size)として読み戻し、Document.get_embedded_file は名前でそれを検索します。FileSpecification.save() は復元されたバイト列をディスクに書き込みます。
from aspose_pdf import Document
with Document() as document:
document.pages.add()
document.add_attachment(
"notes.txt",
b"Reviewed and approved.",
mime="text/plain",
description="Reviewer notes",
)
document.save("with-attachment.pdf")
with Document() as document:
document.load_from("with-attachment.pdf")
for spec in document.embedded_files:
print(spec.name, spec.mime_type, spec.size)
notes = document.get_embedded_file("notes.txt")
if notes is not None:
notes.save("notes-recovered.txt")
フォントの検出と埋め込み
FontRepository はフォントソースを集約し、ドキュメント全体で名前に基づいてフォントを解決します。FontRepository.add_source() は FontSource(例: FolderFontSource)を登録します(ディレクトリをスキャンし、オプションで再帰的に)。FontRepository.find_font() と search() は、ファミリ名、完全名、または PostScript 名でフォントを解決し、標準フォントレジストリへフォールバックします。各一致は FontDescriptor であり、直接 Page.add_text に渡してフォントを埋め込みサブセット化できます。FontRegistry は一般的な非標準名(Arial、Times New Roman など)を search_font_by_name() を介して最も近い Standard-14 の等価物にマッピングします。
from aspose_pdf import Document, FolderFontSource, FontRepository
from aspose_pdf.font_registry import FontRegistry
FontRepository.add_source(FolderFontSource("./fonts", scan_subdirectories=True))
descriptor = FontRepository.find_font("Open Sans")
if descriptor is None:
# Fall back to the closest Standard-14 match for a common font name.
descriptor = FontRegistry().search_font_by_name("Arial")
with Document() as document:
page = document.pages.add()
page.add_text(
"Rendered with a resolved font",
x=72,
y=700,
font_size=14,
font=descriptor,
)
document.save("font-sample.pdf")
ドキュメントアウトラインとブックマーク
Document.outlines は OutlineCollection を返します。これは PDF のブックマークツリーの最上位コンテナです。OutlineCollection.add は最上位の OutlineItem を追加し、OutlineItem.add() は既存のブックマークの下に子ブックマークをネストします。各 OutlineItem は title、対象の page_index、および is_bold / is_italic 表示フラグを保持し、独自の children リストを公開します。
from aspose_pdf import Document
from aspose_pdf.outlines import OutlineItem
with Document() as document:
document.pages.add()
document.pages.add()
chapter = OutlineItem("Chapter 1: Overview", page_index=0)
document.outlines.add(chapter)
chapter.add(OutlineItem("Section 1.1", page_index=0, is_italic=True))
document.outlines.add(OutlineItem("Chapter 2: Details", page_index=1, is_bold=True))
document.save("bookmarked.pdf")
クイックスタート
パッケージをインストールし、単一のスクリプトでブックマーク、ドキュメントメタデータ、添付ファイルを組み合わせた文書を作成します。
asposefoss/pdf is not yet published — build from source until it ships. See the project README for build instructions.from aspose_pdf import Document
from aspose_pdf.outlines import OutlineItem
with Document() as document:
page = document.pages.add()
page.add_text("Quarterly Report", x=72, y=740, font_size=20)
document.outlines.add(OutlineItem("Quarterly Report", page_index=0))
document.info = {"Title": "Quarterly Report"}
document.add_attachment(
"source-data.csv", b"quarter,total\nQ1,1000\n", mime="text/csv"
)
document.save("report.pdf")
with Document() as reopened:
reopened.load_from("report.pdf")
print(reopened.page_count, "page(s),", reopened.info.get("Title"))
print([spec.name for spec in reopened.embedded_files])
サポートされているフォーマット
| フォーマット | 拡張子 | 読み取り | 書き込み |
|---|---|---|---|
| はい | はい | ||
| TIFF | tiff | - | はい |
Page.render、Page.save_as_image、および Document.save_page_as_image は TIFF に加えて PNG ラスター出力も生成します。
これらは文書読み込みフォーマットではなく、ページラスタライズ出力です。
オープンソースとライセンス
Aspose.PDF FOSS for Python は MIT ライセンスの下でリリースされています:使用制限なし、ランタイム料金なし、商用・個人利用ともに登録要件なし。ソースコードは github.com/aspose-pdf-foss/Aspose-PDF-FOSS-for-Python にホストされており、パッケージは PyPI で aspose-pdf-foss-for-python として公開されています。