首页 > 解决方案 > 简单的 PyPDF 练习 - AttributeError:“NullObject”对象没有属性“get”

问题描述

进行一个简单的 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'

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

标签: pythonpypdf2

解决方案


由于某种原因,您的 pdf 文件不包含“/Resources”。PyPDF2 尝试在https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/pdf.py#L2314的第 2314 行获取它

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

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


通过简要查看pdf 文件结构,似乎 /Resources 是可选的。如果是这种情况,那么 PyPDF2 不会处理这种情况,它可能应该在https://github.com/mstamy2/PyPDF2/issues报告为错误


推荐阅读