0

I am trying to get print one page of a PDF to a new PDF document. I am using the following code:

from PyPDF2 import PdfFileReader, PdfFileWriter

file_path = "/file_path/.pdf"

input_pdf = PdfFileReader(file_path)
output_file = PdfFileWriter()

cover_page = input_pdf.getPage(0)
output_file.addPage(cover_page)

with open("portion.pdf", "wb") as output_file:
    output_file.write(output_file)

When I run this code I get the following error:

Traceback (most recent call last):
  File ".../Extract a portion of PDF.py", line 18, in <module>
    output_file.write(output_file)
TypeError: a bytes-like object is required, not '_io.BufferedWriter'

I have specified that the output needs to write binary, so why is it saying that I must use byte-like objects?

Cheers,

1 Answer 1

1

In the with statement, you named the opened file output_file. This essentially reassigned output_file from a PdfFileWriter() to the file stream you just opened. When you tried to do output_file.write(output_file), that's basically trying to write the file stream object itself into the file stream, which makes no sense and causes the TypeError.

To fix this, simply rename the variable you used in the with statement:

with open("portion.pdf", "wb") as output_file_stream:
    output_file.write(output_file_stream)

Alternatively, you can also rename the PdfFileWriter() to output_pdf instead of output_file and change the with statement to something like:

with open("portion.pdf", "wb") as output_file:
    output_pdf.write(output_file)

which might make more sense.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.