使用 PyPdf2 替换 pdf 中的文本

Replacing text in a pdf using PyPdf2

我想使用 PyPdf2 替换 pdf 中特定位置的文本。我试过这个:

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)

但是我得到错误:

TypeError: 'str' object does not support item assignment

有什么办法可以解决这个问题

谢谢,

使用replace()替换文字,例如:

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

此代码将使文本文件替换并保存:

#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()