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

2024-09-27 07:27:18 发布

您现在位置:Python中文网/ 问答频道 /正文

上下文

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

例如

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”,它会工作。 有没有办法只使用相对路径?


Tags: pathkeyinoutputobjectpdfos链接
1条回答
网友
1楼 · 发布于 2024-09-27 07:27:18

在阅读了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()

相关问题 更多 >

    热门问题