Manage PDF Headers and Footers using Python

Create Styled Text Artifacts

This utility function explains how to create a reusable text artifact for PDF pages using Aspose.PDF for Python. It is designed for generating styled headers or footers with consistent formatting, including font settings, color, size, and alignment. The function abstracts artifact creation so it can be reused for different page-level text decorations.

  1. Instantiate the artifact object.
  2. Set artifact text content.
  3. Apply text styling.
  4. Set alignment.
  5. Return configured artifact.
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

Add Header to PDF

  1. Open the input PDF.
  2. Create a HeaderArtifact with text “Sample Header”.
  3. Append it to the first page.
  4. Save the updated 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)
  1. Open the input PDF.
  2. Create a FooterArtifact with text “Sample Footer”.
  3. Append it to the first page.
  4. Save the output file.
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. Open the PDF.
  2. Find artifacts marked as pagination headers or footers.
  3. Remove them from the first page.
  4. Save the cleaned document.
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)