I am using Python 3.6.5
to merge PDFs together but am running into a problem. The code below throws a 'TypeError: 'NumberObject' object is not subscriptable'
error. What am I doing wrong? When I comment out the line with the merger.append
, it prints out the file paths correctly.
import webbrowser
import os
from PyPDF2 import PdfFileMerger, PdfFileReader
path = 'C:/test/pdfs'
merger = PdfFileMerger()
for pdf in os.listdir(path):
merger.append(PdfFileReader(open(os.path.join(path,pdf), 'rb')))
print(os.path.join(path,pdf))
merger.write(path+'/merged.pdf')
merger.close()
webbrowser.open_new(path+'/merged.pdf')
File "C:\test\pdftest.py", line 9, in merger.append(PdfFileReader(open(os.path.join(path,pdf), 'rb'))) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\pdf.py", line 1084, in init self.read(stream) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\pdf.py", line 1805, in read assert xrefstream["/Type"] == "/XRef" TypeError: 'NumberObject' object is not subscriptable
When I change the merger.append to take a file path, I get:
File "C:\test\pdftest.py", line 9, in merger.append(os.path.join(path,pdf)) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\merger.py", line 203, in append self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\merger.py", line 133, in merge pdfr = PdfFileReader(fileobj, strict=self.strict) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\pdf.py", line 1084, in init self.read(stream) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\pdf.py", line 1805, in read assert xrefstream["/Type"] == "/XRef" TypeError: 'NumberObject' object is not subscriptable
UPDATE: It looks like one of the PDFs in the folder was causing this. The only thing different with that PDF is that it uses Type 1 font whereas the other PDFs use TrueType font. Does anyone know a workaround or fix for this?
path
are not files and are not PDF files. You need to filter those out from the result ofos.listdir(path)
. – Dan D.