简介
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 通过 search_font_by_name() 将常见的非标准名称(Arial、Times New Roman 等)映射到最接近的 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也会生成 PNG 栅格输出以及 TIFF。
这些是页面栅格化输出,而非文档加载格式。
开源与许可
Aspose.PDF FOSS 用于 Python 在 MIT 许可证下发布:无使用限制、无运行时费用,且商业或个人使用均无需注册。源代码托管在 github.com/aspose-pdf-foss/Aspose-PDF-FOSS-for-Python,该软件包在 PyPI 上发布,名称为 aspose-pdf-foss-for-python。