Trying to write a function to combine pages in a PDF document. Streaming the output creates a blank page for an unknown reason Here is the test case
from PyPDF2 import PdfReader, PdfWriter
dr = r"C:\GC"
ldr = dr + r"\12L.pdf"
writer = PdfWriter()
with open(ldr, "rb") as f:
reader = PdfReader(f)
page = reader.pages[0]
writer.add_page(page)
f.close()
with open(dr + r"\new.pdf", "wb") as output_stream:
writer.write(output_stream)
output_stream.close()
Edit: I made some changes to my PE and got more information.
writer.write(output_stream)
raises the error
ValueError: I/O operation on closed file: C:\GC\12L.pdf
I did some troubleshooting with keeping the reader file open and changing syntax to suggestions and I still raise the error.
Since you're using a context manager, you don't need to explicitly call .close()
. Try this:
from PyPDF2 import PdfReader, PdfWriter
dr = r"C:\GC"
ldr = dr + r"\12L.pdf"
writer = PdfWriter()
with open(ldr, "rb") as f:
reader = PdfReader(f)
page = reader.pages[0]
writer.add_page(page)
with open(dr + r"\new.pdf", "wb") as output_stream:
writer.write(output_stream)