使用 Python 在已有 PDF 文件中替换图像
Contents
[
Hide
]
在 PDF 中替换图像
当您需要在 PDF 中更新徽标、图表或其他嵌入式图形且无需重新构建文档布局时,请使用此页面。
- 使用加载源 PDF
ap.Document(infile). - 将替换图像以二进制流的形式打开。
- 按索引在页面上替换图像资源。
- 保存更新后的 PDF。
import aspose.pdf as ap
from io import FileIO
def replace_image(infile, image_file, outfile):
document = ap.Document(infile)
with FileIO(image_file, "rb") as image_stream:
document.pages[1].resources.images.replace(1, image_stream)
document.save(outfile)
替换特定图像
此示例替换由…找到的特定图像放置 ImagePlacementAbsorber.
- 加载源 PDF。
- 创建
ImagePlacementAbsorber并收集页面上的图像放置位置。 - 检查页面上是否存在任何图像位置。
- 用新的图像流替换所选位置。
- 保存更新后的 PDF。
import aspose.pdf as ap
from io import FileIO
def replace_image_with_absorber(infile, image_file, outfile):
document = ap.Document(infile)
absorber = ap.ImagePlacementAbsorber()
document.pages[1].accept(absorber)
if len(absorber.image_placements) > 0:
image_placement = absorber.image_placements[1]
with FileIO(image_file, "rb") as image_stream:
image_placement.replace(image_stream)
document.save(outfile)