我试图附加一个包含名称和页码的书签,但我无法让它用书签保存文件。
这是代码:
import PyPDF2 as pdf
import os
pth = r'D:\Haymovich\pythonScriptTry\pdf\old'
save_pth = r'D:\Haymovich\pythonScriptTry\pdf\new\MainPDF.pdf'
def pdf_marge(inp):
mar = pdf.PdfFileMerger()
for num, eachPDF in enumerate(os.listdir(inp)):
eachPDF2 = os.path.join(pth, eachPDF)
eachPDF3 = eachPDF.replace('.pdf', '')
bookMark = mar.addBookmark(title=eachPDF3, pagenum=num)
mar.append(fileobj=eachPDF2, bookmark=bookMark)
return mar.write(save_pth)
print(pdf_marge(pth))
这是书签:
{'/Title': 'NESS01-2020', '/Page': 0, '/Type': '/FitH', '/Top': 826}
{'/Title': 'NESS01-2021', '/Page': 1, '/Type': '/FitH', '/Top': 826}
{'/Title': 'NESS02-2020', '/Page': 2, '/Type': '/FitH', '/Top': 826}
{'/Title': 'NESS03-2020', '/Page': 3, '/Type': '/FitH', '/Top': 826}
如何保存带书签的 PDF?
您没有打开文件
改变
return mar.write(save_pth)
至
with open(save_pth, "wb") as new_pdf:
mar.write(new_pdf)