TypeError: 'PdfFileWriter' object is not callable

1.5k Views Asked by At

I am trying to extract specific pages from a PDF file, and save it in a different file name. Followed the codes provided here : https://www.youtube.com/watch?v=W6Gt57b3Pp4&t=219s

from PyPDF2 import PdfFileReader, PdfFileWriter
pdf_file_path = "oranges.pdf"
file_base_name = pdf_file_path.replace(".pdf","")

pdf = PdfFileReader(pdf_file_path) #Creating PDF instance
pages = [0,2,4]

pdfwriter = PdfFileWriter() #Creating pdfWriter instance
print

for page_num in pages:
    pdfwriter().addPage(pdf.getPage(page_num))
with open("{0}_subset".format(file_base_name),'wb') as f:
    pdfwriter.write(f)
    f.close

However I am getting this error in line 12: TypeError: 'PdfFileWriter' object is not callable How should I resolve this error?

1

There are 1 best solutions below

0
On BEST ANSWER

You cannot call a method invocation on an object unless the object points to a method.

Change the line pdfwriter().addPage() to pdfwriter.addPage()

from PyPDF2 import PdfFileReader, PdfFileWriter
pdf_file_path = "oranges.pdf"
file_base_name = pdf_file_path.replace(".pdf","")

pdf = PdfFileReader(pdf_file_path) #Creating PDF instance
pages = [0,2,4]

pdfwriter = PdfFileWriter() #Creating pdfWriter instance


for page_num in pages:
    pdfwriter.addPage(pdf.getPage(page_num))

with open("{0}_subset".format(file_base_name),'wb') as f:
    pdfwriter.write(f)
    f.close()