使用 Python 管理 PDF 页眉和页脚
Contents
[
Hide
]
创建样式化文本痕迹
此实用函数说明了如何使用 Aspose.PDF for Python 为 PDF 页面创建可重用的文本工件。它旨在生成具有一致格式的样式化页眉或页脚,包括字体设置、颜色、大小和对齐方式。该函数对工件的创建进行抽象,以便在不同的页面级文本装饰中重复使用。
- 实例化工件对象。
- 设置工件文本内容。
- 应用文本样式。
- 设置对齐。
- 返回已配置的工件。
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 添加页眉
- 打开输入的 PDF。
- 创建一个 HeaderArtifact,文本为 “Sample Header”。
- 将其追加到第一页。
- 保存更新后的 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 添加页脚
- 打开输入的 PDF。
- 创建一个 FooterArtifact,文本为 “Sample Footer”。
- 将其追加到第一页。
- 保存输出文件。
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)
删除页眉或页脚工件
- 打开 PDF。
- 查找标记为分页页眉或页脚的伪件。
- 将它们从首页中移除。
- 保存已清理的文档。
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)