The following code tries to edit part of text in a PDF file:
from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.generic import DecodedStreamObject, EncodedStreamObject
in_file="input.pdf"
pdf = PdfFileReader(in_file)
#Just first page is subjected to be edited
page=pdf.pages[0]
contents=page["/Contents"]
#contents[1] is a IndirectObject of PyPDF2, so EncodedStreamObject can be obtained by get_object()
ogg=contents[1].get_object()
#obtaining byte datas
enc_data=ogg.get_data()
#decoding (in string) in order to be editable
dec_data=enc_data.decode('utf-8')
new_dec_data=dec_data.replace("old text string","new text string")
#returning to bytes format but with new text replaced
new_enc_data=new_dec_data.encode('utf-8')
#HERE is the problem !
#Looking in script lib i couldnt resolve the final step. setData() doesnt work as it should.
ogg.decodedSelf.setData( new_enc_data)
#print(ogg)
writer = PdfFileWriter()
writer.addPage(page)
with open("output.pdf", 'wb') as out_file:
writer.write(out_file)
Of course output.pdf corresponds to original input pdf file.
Just linking the interested object : https://fossies.org/dox/openslides-2.3-portable/classPyPDF2_1_1generic_1_1EncodedStreamObject.html
Has anyone else experienced the same problem ?
Maybe im not understanding actual issue.