如何在 Python 中加载文档
Aspose.PDF FOSS for Python 将 PDF 从文件路径、原始字节或二进制流加载到一个 Document 对象中,您可以检查和操作该对象。该库是纯 Python,只需一条命令即可安装。
分步指南
步骤 2:导入所需类
导入 Document 以加载和持有 PDF,以及在加载失败时需要处理的异常类:
from aspose_pdf import (
Document,
InvalidPasswordException,
InvalidPdfFileFormatException,
PdfCorruptedError,
PdfParseException,
)步骤 3:从文件路径加载 PDF
直接将文件路径传递给 Document 构造函数,或在已有实例上显式调用 load_from —— 两者都接受路径、bytes 或二进制流。使用 Document 作为上下文管理器,以便自动释放底层文件句柄:
from aspose_pdf import Document
with Document("report.pdf") as document:
print(f"Loaded {document.page_count} page(s)")构造函数形式 Document(source) 等价于 Document().load_from(source):
document = Document()
document.load_from("report.pdf")
print(f"Loaded {document.page_count} page(s)")
document.close()步骤 4:加载受密码保护的 PDF
Document(source, password=...) 和 Document.load_from(source, password, limits) 都接受一个用于用户密码加密的 PDF 的 password 参数:
from aspose_pdf import Document
with Document("locked.pdf", password="secret") as document:
print(f"Opened encrypted document: {document.page_count} page(s)")
print(f"Encrypted: {document.is_encrypted}")如果源文件没有密码保护,请省略该参数——传入 password=None(默认值)同样适用于普通 PDF。
步骤 5:处理加载异常
文件缺失、非 PDF 数据、密码缺失或错误、或 PDF 损坏时,永远不会悄悄返回空的 Document——而是抛出异常。请捕获具体的异常类以作出相应处理:
from aspose_pdf import (
Document,
InvalidPasswordException,
InvalidPdfFileFormatException,
PdfCorruptedError,
PdfParseException,
)
try:
document = Document("report.pdf", password="maybe-wrong")
except InvalidPasswordException:
print("The PDF is encrypted; supply the correct password.")
except InvalidPdfFileFormatException:
print("The file is not a valid PDF.")
except PdfCorruptedError as error:
print(f"Unrecoverable corruption at offset {error.offset}: {error.message}")
except PdfParseException as error:
print(f"Could not parse the PDF: {error}")
else:
print(f"Loaded {document.page_count} page(s)")
document.close()PdfCorruptedError 及其兄弟 PdfMalformedError 都包含 message、offset 和 recoverable 属性,这对于精确记录破损文件在哪一步解析失败非常有用。处理不可信输入时,还应捕获 PdfResourceLimitException,该异常在文档超出默认的 PdfLoadLimits 安全策略(输入大小、对象数量、解码流大小等限制)时被抛出。
步骤 7:释放文档资源
使用 Document 作为上下文管理器(with Document(...) as document:)时,块退出后会自动关闭文档。当在 with 块之外构造 Document 时,请在完成后显式调用 close() 或 dispose()。
document = Document()
document.load_from("report.pdf")
try:
print(document.page_count)
finally:
document.close()常见问题与解决方案
InvalidPasswordException 即使我认为文件没有加密,也会被抛出
源 PDF 设置了用户密码。请与文件来源确认此情况,然后将正确的值作为 password 参数传递给 Document(...) 或 load_from(...)。
InvalidPdfFileFormatException 在看起来正常的文件上
该文件不是有效的 PDF——可能是 HTML 错误页面、下载不完整,或是以 .pdf 扩展名保存的其他格式。请在文本编辑器中打开文件,确认其以 %PDF- 开头。
PdfCorruptedError 在其他查看器能够打开的文件上
一些 PDF 阅读器会悄悄修复损坏的结构。Document 会在不可恢复的损坏时抛出 PdfCorruptedError,在可恢复的结构问题时抛出 PdfMalformedError——检查异常上的 offset 属性以定位字节流中的问题区域。
PdfResourceLimitException 在大型或复杂的 PDF 上
文档超出了默认的 PdfLoadLimits 限界(输入大小、对象计数、解码流大小等旨在防御不可信输入的限制)。构建自定义的 PdfLoadLimits 并将其作为 limits= 传递给 Document(...),如果文件可信且需要更大的限制,则传递给 load_from(...)。
忘记关闭 Document 在外部打开 with block
完成后调用 document.close()(或 document.dispose()),或者使用 with Document(source) as document: 加载文件,这样即使块内部出现异常,也会自动进行清理。
常见问题
在加载 PDF 时,我可以将什么作为 source 参数传入?
Document(source) 和 Document.load_from(source, password, limits) 接受文件路径、原始 bytes,或任何二进制流。
我该如何加载已经在内存中的 PDF,而不是从磁盘加载?
直接传递 bytes 对象:Document(pdf_bytes),或对已有的 Document 实例调用 document.load_from(pdf_bytes)。
加载 PDF 是否必须事先提供正确的密码,还是可以先进行检查?
is_encrypted 仅在成功加载后可用,因此加密的 PDF 必须在同一次调用中使用正确的 password 参数打开。如果需要交互式提示密码,请捕获 InvalidPasswordException。