如何解决简单的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'
我将不胜感激。我已经凝视了一段时间了。
解决方法
由于某种原因,您的pdf文件不包含“ /资源”。 PyPDF2试图在https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/pdf.py#L2314
的第2314行中获取它您可以尝试另一个pdf文件来检查错误是否仍然存在。可能是库中的错误,或者库不支持此类文件。
我注意到的另一件事是,库的master分支中的行号与您的堆栈跟踪中的行号不匹配,因此可能是您需要获取该库的最新版本,并希望在那里解决此问题。 / p>
通过简要查看pdf file structure,似乎/ Resources是可选的。如果是这种情况,则PyPDF2无法处理这种情况,应该在https://github.com/mstamy2/PyPDF2/issues
处将其报告为错误。版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。