如何使用 pypdf 在 pdf 中添加相对文件路径

How to add a relative file path inside a pdf using pypdf

上下文

  1. 我有一个带有链接的 pdf。
  2. 我想用同一文件夹中的本地文件替换所有外部链接。
  3. 有没有办法在 pypdf 或 python
  4. 中做到这一点

例如

outputStream = open("destination.pdf", "wb")
key = '/Annots'
uri = '/URI'
ank = '/A'
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
cwd = os.getcwd()
for x in range(existing_pdf.getNumPages()):
    page = existing_pdf.getPage(x)
    page_object = page.getObject()

    if key in page_object:
        ann = page_object[key]
        for a in ann:
            u = a.getObject()
            if uri in u[ank]:
                test = u[ank][uri]
                test1 = u[ank].keys()
                u[TextStringObject(ank)][TextStringObject(uri)] = TextStringObject(f"file:./foo1.pdf")
    output.addPage(page)
    # finally, write "output" to a real file
    output.write(outputStream)
outputStream.close()

以上不起作用,即 foo1.pdf 链接不正确。 如果我添加“file:///{CWD}/foo1.pdf”,它就会起作用。 有没有办法只使用相对路径?

阅读 pdf 结构和文档后,我能够编写以下内容并且它按预期工作。

   for x in range(existing_pdf.getNumPages()):
    page = existing_pdf.getPage(x)
    page_object = page.getObject()
    if key in page_object:
        ann = page_object[key]
        for a in ann:
            u = a.getObject()
            if uri in u[ank]:
                del u[TextStringObject(ank)][TextStringObject(uri)]
                u[TextStringObject(ank)][NameObject('/F')] = TextStringObject(f"./sheets/sheet1.pdf")
                u[TextStringObject(ank)][TextStringObject('/S')] = NameObject("/Launch")
                u[TextStringObject(ank)][NameObject('/NewWindow')] = BooleanObject(f"true")
    output.addPage(page)
    # finally, write "output" to a real file
    output.write(outputStream)
outputStream.close()