介绍
PostScript(PS)和封装的 PostScript(EPS)是用于打印工作流、传统出版系统和图形流水线的矢量文档格式。面向 Python 的 Aspose.Page FOSS 提供了 PsDocument——一个能够同时处理 .ps 和 .eps 文件的单一类——并提供方法直接从 Python 代码将它们导出为 PDF 或栅格图像。
该库不需要 Ghostscript 安装,不需要 Adobe 运行时,也不依赖本地系统库。它可在 Windows、Linux 和 macOS 上运行。使用 pip 安装后即可在任何 Python 3.10+ 环境中立即使用。
加载 PS 和 EPS 文件
PsDocument 提供两个类方法用于加载文档。from_file() 从文件路径读取;from_bytes() 接受来自流或上传的原始字节。
from aspose.page.ps.document import PsDocument
# Load from file path
ps = PsDocument.from_file("document.ps")
eps = PsDocument.from_file("illustration.eps")
# Load from bytes (network stream, upload, etc.)
with open("document.ps", "rb") as f:
data = f.read()
ps_from_bytes = PsDocument.from_bytes(data)
如果文档是 EPS 文件,is_eps 属性将返回 True,这在通过相同代码路径处理混合的 PS 和 EPS 文件批次时非常有用。
导出为 PDF
在已加载的 PsDocument 上调用 to_pdf() 以获取 bytes 对象形式的输出。结果是一个有效的 PDF 字节流,可写入磁盘、存储到数据库,或从 HTTP 端点返回。
from pathlib import Path
from aspose.page.ps.document import PsDocument
ps = PsDocument.from_file("input.ps")
pdf_bytes = ps.to_pdf()
Path("output.pdf").write_bytes(pdf_bytes)
默认的 PDF 导出不需要 options 对象。to_pdf() 方法接受可选的 options 参数,以满足高级使用场景。
导出为光栅图像
要将 PS 或 EPS 文档渲染为光栅图像,请将 ImageSaveOptions 实例传递给 to_image()。将 format 设置为 "png" 或 "jpeg",并使用 dpi 控制输出分辨率。该方法返回包含已编码图像的 bytes 对象。
from pathlib import Path
from aspose.page.ps.document import PsDocument
from aspose.page.ps.output import ImageSaveOptions
eps = PsDocument.from_file("illustration.eps")
opts = ImageSaveOptions(format="png", dpi=150)
png_bytes = eps.to_image(opts)
Path("output.png").write_bytes(png_bytes)
若要输出 JPEG,请修改 format="jpeg"。当未设置时,dpi 属性默认值为 96。
读取 EPS 元数据
PsDocument 暴露一个 dsc 属性,当文件中存在 DSC 注释时返回一个 DscMetadata 实例。DscMetadata 提供对从 EPS 头部解析出的边界框坐标、页面尺寸、方向、标题和创建者字段的结构化访问。
from aspose.page.ps.document import PsDocument
eps = PsDocument.from_file("illustration.eps")
dsc = eps.dsc
if dsc is not None:
print("Title:", dsc.title)
print("Bounding box:", dsc.bounding_box)
print("HiRes bounding box:", dsc.hires_bounding_box)
批量转换
因为所有转换方法返回 bytes 并接受文件路径或原始字节作为输入,批处理可以使用标准的 Python 循环或 concurrent.futures 直接实现。
from pathlib import Path
from aspose.page.ps.document import PsDocument
input_dir = Path("ps-files")
output_dir = Path("pdf-output")
output_dir.mkdir(exist_ok=True)
for ps_file in input_dir.glob("*.ps"):
doc = PsDocument.from_file(str(ps_file))
out_path = output_dir / ps_file.with_suffix(".pdf").name
out_path.write_bytes(doc.to_pdf())
print("Converted:", ps_file.name)
通过将全局模式更改为 "*.eps",相同的模式同样适用于 EPS 文件。