PyPDF2.errors.DeprecationError: PdfFileWriter is deprecated and was removed in PyPDF2 3.0.0. Use PdfWriter instead.
Assistant
The error you're encountering indicates that your code is using an outdated class or method from the PyPDF2 library. Specifically, PdfFileWriter has been deprecated and removed as of PyPDF2 version 3.0.0. You should replace it with PdfWriter.
Here's how you can update your Python script to resolve this error:
Before (using PyPDF2 with PdfFileWriter)
python
import PyPDF2
# Create PDF file writer
pdf_writer = PyPDF2.PdfFileWriter()
# Example of adding a page
input_pdf = PyPDF2.PdfFileReader("input.pdf")
page = input_pdf.getPage(0)
pdf_writer.addPage(page)
# Write to a new file
with open("output.pdf", "wb") as output_pdf:
pdf_writer.write(output_pdf)
After (using PyPDF2 with PdfWriter)
python
import PyPDF2
# Create PDF writer
pdf_writer = PyPDF2.PdfWriter()
# Example of adding a page
input_pdf = PyPDF2.PdfReader("input.pdf")
page = input_pdf.pages[0]
pdf_writer.add_page(page)
# Write to a new file
with open("output.pdf", "wb") as output_pdf:
pdf_writer.write(output_pdf)
Key Changes to Note:
Class Name Change: Replace PdfFileWriter() with PdfWriter().
Class Name Change for Reading PDFs: Replace PdfFileReader() with PdfReader().
Attribute Changes: For accessing pages in PdfReader, use pages instead of getPage() or similar methods. It returns a list-like object of pages.
Method Changes: Instead of addPage(page), use add_page(page).
Additional Tips:
Always ensure that your library is updated to the latest version, though be mindful of new changes and deprecations. You can update PyPDF2 using pip:
bash
pip install --upgrade PyPDF2
Check the PyPDF2 documentation or GitHub page for latest updates or changes if you encounter further issues.
By making these adjustments, your code should run without deprecation errors, allowing you to utilize the latest features of the PyPDF2 library more effectively.
import PyPDF2
def merge_pdfs(paths, output):
pdf_writer = PyPDF2.PdfWriter()
for path in paths:
pdf_reader = PyPDF2.PdfReader(path)
for page in range(len(pdf_reader.pages)):
# Add each page to the writer object
pdf_writer.add_page(pdf_reader.pages[page])
# Write out the merged PDF
with open(output, 'wb') as out:
pdf_writer.write(out)
if __name__ == '__main__':
# Paths to the PDF files
paths = ['file1.pdf', 'file2.pdf']
output = 'merged.pdf'
merge_pdfs(paths, output)
print("PDFs have been merged successfully!")