Python を使用して PDF ヘッダーとフッターを管理する

スタイル付きテキストアーティファクトの作成

このユーティリティ関数は、Aspose.PDF for Python を使用して PDF ページ用の再利用可能なテキストアーティファクトを作成する方法を説明します。フォント設定、色、サイズ、配置など、一貫したフォーマットでスタイル付きのヘッダーまたはフッターを生成するように設計されています。この関数はアーティファクトの作成を抽象化して、さまざまなページレベルのテキスト装飾に再利用できます。

  1. アーティファクトオブジェクトをインスタンス化します。
  2. アーティファクトのテキストコンテンツを設定します。
  3. テキストスタイルを適用します。
  4. 配置を設定します。
  5. 設定済みのアーティファクトを返します。
from os import path
import aspose.pdf as ap
import sys

def _create_text_artifact(artifact_class, text):
    """Create a text artifact (header/footer) with common styling."""
    artifact = artifact_class()
    artifact.text = text
    artifact.text_state.font_size = 14
    artifact.text_state.font = ap.text.FontRepository.find_font("Arial")
    artifact.text_state.foreground_color = ap.Color.navy
    artifact.artifact_horizontal_alignment = ap.HorizontalAlignment.CENTER
    return artifact

PDF にヘッダーを追加

  1. 入力 PDF を開きます。
  2. 「サンプルヘッダー」というテキストを含むヘッダーアーティファクトを作成します。
  3. 最初のページに追加してください。
  4. 更新した PDF を保存します。
from os import path
import aspose.pdf as ap
import sys

def add_header_artifact(infile, outfile):
    """Add a header artifact to the first page of a PDF document."""
    with ap.Document(infile) as document:
        header = _create_text_artifact(ap.HeaderArtifact, "Sample Header")
        document.pages[1].artifacts.append(header)
        document.save(outfile)

PDF にフッターを追加

  1. 入力 PDF を開きます。
  2. 「サンプルフッター」というテキストを含むフッターアーティファクトを作成します。
  3. 最初のページに追加してください。
  4. 出力ファイルを保存します。
from os import path
import aspose.pdf as ap
import sys

def add_footer_artifact(infile, outfile):
    """Add a footer artifact to the first page of a PDF document."""
    with ap.Document(infile) as document:
        footer = _create_text_artifact(ap.FooterArtifact, "Sample Footer")
        document.pages[1].artifacts.append(footer)
        document.save(outfile)

ヘッダーまたはフッターのアーティファクトを削除

  1. PDF を開きます。
  2. ページネーションヘッダーまたはフッターとしてマークされたアーティファクトを検索します。
  3. 最初のページから削除してください。
  4. クリーニングした文書を保存します。
from os import path
import aspose.pdf as ap
import sys

def delete_header_footer_artifact(infile, outfile):
    with ap.Document(infile) as document:
        header_footers = [
            artifact
            for artifact in document.pages[1].artifacts
            if artifact.type == ap.Artifact.ArtifactType.PAGINATION
            and (
                artifact.subtype == ap.Artifact.ArtifactSubtype.HEADER
                or artifact.subtype == ap.Artifact.ArtifactSubtype.FOOTER
            )
        ]

        for art in header_footers:
            document.pages[1].artifacts.delete(art)

        document.save(outfile)

アーティファクトの関連トピック