Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

python - Replacing text in a pdf using PyPdf2

I want to replace text at a particular location in a pdf using PyPdf2. I tried this:

import PyPDF2 as pdf
filename = 'C:/Users/Workstation/Downloads/Sample Text.pdf'
Report = open(filename, 'rb') 
pdfReader = pdf.PdfFileReader(Report)
pageObj = pdfReader.getPage(0)
txt = pageObj.extractText() 

name = txt[34]
print("name: "+name)
txt[72:80] = "solarsys" #Replacement of text
star_sys = txt[71:83]
print("star_system: "+star_sys)

But I get the error:

TypeError: 'str' object does not support item assignment

Is there any way to get around this

Thanks,

question from:https://stackoverflow.com/questions/65902765/replacing-text-in-a-pdf-using-pypdf2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the replace() to replace the text, for example:

newTxt = txt.replace('#what word you want to repalce', '# which word you want to replace it with')

and this code will make the text file replace and save:

#input file
test = open("Test.txt", "w+")
#output file to write the result to
test2 = open("Test2.txt", "wt")
#for each line in the input file
for line in test:
    #read replace the string and write to output file
    test2.write(line.replace('replace', 'replaced'))
#close input and output files
test.close()
test2.close()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...