Python 简单PyPDF练习-属性错误:';空对象';对象没有属性';获取';

Python 简单PyPDF练习-属性错误:';空对象';对象没有属性';获取';,python,pypdf2,Python,Pypdf2,做一个简单的PyPDF相关的练习-我基本上需要拿一个PDF文件并对其应用水印 这是我的密码: # We need to build a program that will watermark all of our PDF files # Use the wtr.pdf and apply it to all of the pages of our PDF file import PyPDF2 # Open the file we want to add the watermark to wi

做一个简单的PyPDF相关的练习-我基本上需要拿一个PDF文件并对其应用水印

这是我的密码:

# We need to build a program that will watermark all of our PDF files
# Use the wtr.pdf and apply it to all of the pages of our PDF file

import PyPDF2

# Open the file we want to add the watermark to
with open("combined.pdf", mode="rb") as file:
    reader = PyPDF2.PdfFileReader(file)

    # Open the watermark file and get the watermark 
    with open("wtr.pdf", mode="rb") as watermark_file:
        watermark_reader = PyPDF2.PdfFileReader(watermark_file)        

        # Create a writer object for the output file
        writer = PyPDF2.PdfFileWriter()        

        for i in range(reader.numPages):
            page = reader.getPage(i)
            # Merge the watermark page object into our current page
            page.mergePage(watermark_reader.getPage(0))
            # Append this new page into our writer object
            writer.addPage(page)

        with open("watermarked.pdf", mode="wb") as output_file:
            writer.write(output_file)
我不清楚为什么会出现这个错误:

$ python watermark.py
Traceback (most recent call last):
  File "watermark.py", line 20, in <module>
    page.mergePage(watermark_reader.getPage(0))
  File "C:\Python38\lib\site-packages\PyPDF2\pdf.py", line 2239, in mergePage
    self._mergePage(page2)
  File "C:\Python38\lib\site-packages\PyPDF2\pdf.py", line 2260, in _mergePage
    new, newrename = PageObject._mergeResources(originalResources, page2Resources, res)
  File "C:\Python38\lib\site-packages\PyPDF2\pdf.py", line 2170, in _mergeResources
    newRes.update(res1.get(resource, DictionaryObject()).getObject())
AttributeError: 'NullObject' object has no attribute 'get'
$python watermark.py
回溯(最近一次呼叫最后一次):
文件“watermark.py”,第20行,在
page.mergePage(水印\读卡器.getPage(0))
文件“C:\Python38\lib\site packages\PyPDF2\pdf.py”,第2239行,在合并页面中
自合并页面(第2页)
文件“C:\Python38\lib\site packages\PyPDF2\pdf.py”,第2260行,位于第页
new,newrename=PageObject.\u合并资源(原始资源,page2Resources,res)
文件“C:\Python38\lib\site packages\PyPDF2\pdf.py”,第2170行,在\u mergeResources中
newRes.update(res1.get(资源,DictionaryObject()).getObject())
AttributeError:“NullObject”对象没有属性“get”

如果您有任何见解,我将不胜感激。我已经盯着这个看了一段时间。

出于某种原因,您的pdf文件不包含“/Resources”。PyPDF2尝试将其放入第2314行

您可以尝试另一个pdf文件来检查错误是否仍然存在。可能是库中存在缺陷,或者库不支持此类文件

我注意到的另一件事是,库的master分支中的行号与堆栈跟踪中的行号不匹配,因此您可能需要获取库的最新版本,并希望问题在那里得到解决



简单地看一下,似乎/资源是可选的。如果是这种情况,那么PyPDF2不会处理这种情况,它可能会在

上报告为错误。请确保pdf与您的代码位于同一目录中。谢谢您的建议。它们在同一个目录中。更新。我尝试更新到PyPDF3,但得到了相同的错误。谢谢你的建议。看来PyPDF3只是PyPDF2的一个老版本,不适合升级。