Manage PDF Headers and Footers using Python
Contents
[
Hide
]
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.
- Instantiate the artifact object.
- Set artifact text content.
- Apply text styling.
- Set alignment.
- 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
- Open the input PDF.
- Create a HeaderArtifact with text “Sample Header”.
- Append it to the first page.
- 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)
Add Footer to PDF
- Open the input PDF.
- Create a FooterArtifact with text “Sample Footer”.
- Append it to the first page.
- 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)
Delete Header or Footer Artifacts
- Open the PDF.
- Find artifacts marked as pagination headers or footers.
- Remove them from the first page.
- 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)