Saturday 13 May 2023

module 'PyPDF2' has no attribute 'ContentStream' error

I am trying to run the following code to replace text inside a PDF file:

import os
import re
import PyPDF2
from io import StringIO

# Define a function to replace text in a PDF file
def replace_text_in_pdf(input_pdf_path, output_pdf_path, search_text, replace_text):
    # Open the input PDF file in read-binary mode
    with open(input_pdf_path, 'rb') as input_file:
        # Create a PDF reader object
        pdf_reader = PyPDF2.PdfReader(input_file)
        
        # Create a PDF writer object
        pdf_writer = PyPDF2.PdfWriter()
        
        # Iterate through each page of the PDF
        for page_num in range(len(pdf_reader.pages)):
            # Get the page object
            page = pdf_reader.pages[page_num]
            
            # Get the text content of the page
            text = page.extract_text()
            
            # Replace the search text with the replace text
            new_text = re.sub(search_text, replace_text, text)
            
            # Create a new page with the replaced text
            new_page = PyPDF2.PageObject.create_blank_page(None, page.mediabox.width, page.mediabox.height)
            new_page.merge_page(page)  # Copy the original page content to the new page
            new_page.add_transformation(PyPDF2.Transformation().translate(0, 0).scale(1, 1))  # Reset the transformation matrix
            
            # Begin the text object
            new_page._text = PyPDF2.ContentStream(new_page.pdf)
            new_page._text.beginText()
            
            # Set the font and font size
            new_page._text.setFont("Helvetica", 12)
            
            # Draw the new text on the page
            x, y = 100, 100  # Replace with the desired position of the new text
            new_page._text.setFontSize(12)
            new_page._text.textLine(x, y, new_text)
            
            # End the text object
            new_page._text.endText()
            
            # Add the new page to the PDF writer object
            pdf_writer.addPage(new_page)
        
        # Save the new PDF file
        with open(output_pdf_path, 'wb') as output_file:
            pdf_writer.write(output_file)

# Call the function to replace text in a PDF file
input_pdf_path = r'D:\file1.pdf'  # Replace with your input PDF file path
output_pdf_path = r'D:\file1_replaced.pdf'  # Replace with your output PDF file path
search_text = '<FirstName>'  # Replace with the text you want to replace
replace_text = 'John'  # Replace with the text you want to replace it with
replace_text_in_pdf(input_pdf_path, output_pdf_path, search_text, replace_text)

However, line: new_page._text = PyPDF2.ContentStream(new_page.pdf) is giving me the following error: module 'PyPDF2' has no attribute 'ContentStream'.

Can someone help how to fix it?



from module 'PyPDF2' has no attribute 'ContentStream' error

No comments:

Post a Comment