【问题标题】:How to add image to PDF file in Python?如何在 Python 中将图像添加到 PDF 文件?
【发布时间】:2012-11-07 19:03:33
【问题描述】:

我有一个 PDF 文档,但我必须在上面放上我自己的图片。这是官方文档,我必须将带有“示例”文本的图像应用到整个页面。

有没有办法在python中解决这个问题?

(文档中的文字是曲线)

【问题讨论】:

  • 大约一个月前我遇到了类似的问题,但在 Python 中无法轻松找到解决方案。现在写一个答案。

标签: python pdf


【解决方案1】:

如果您来自 Google,PyPDF 已被 PyPDF2 取代。语法有所改变。

import PyPDF2 as pypdf

with open("original.pdf", "rb") as inFile, open("overlay.pdf", "rb") as overlay:
    original = pypdf.PdfFileReader(inFile)
    background = original.getPage(0)
    foreground = pypdf.PdfFileReader(overlay).getPage(0)

    # merge the first two pages
    background.mergePage(foreground)

    # add all pages to a writer
    writer = pypdf.PdfFileWriter()
    for i in range(original.getNumPages()):
        page = original.getPage(i)
        writer.addPage(page)

    # write everything in the writer to a file
    with open("modified.pdf", "wb") as outFile:
        writer.write(outFile)

【讨论】:

【解决方案2】:

查看PyPDF。您可以使用类似以下代码的代码来应用叠加层:

page = PdfFileReader(file("document.pdf", "rb")).getPage(0)
overlay = PdfFileReader(file("overlay.pdf", "rb")).getPage(0)
page.mergePage(overlay)

将您想要的任何叠加层(包括“示例”)放入overlay.pdf。 就个人而言,我更喜欢 PDFTK,虽然它不是严格意义上的 Python,但可以从带有 os.system(command) 的脚本中调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 2017-12-19
    • 2021-04-09
    • 2022-07-15
    • 2023-02-22
    • 1970-01-01
    • 2021-10-05
    相关资源
    最近更新 更多