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



上下文

  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";它是有效的。是否有只使用相对路径的方法

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

最新更新