title: Replace text in PDF with Python
body: <p>I am trying to replace text strings in a PDF file using the Python code below.</p>
  <pre><code>import PyPDF2
  reader = PyPDF2.PdfFileReader('document.pdf', strict=True, warndest=None, overwriteWarnings=True)
  writer = PyPDF2.PdfFileWriter()
  replacements = {'old' : 'new'}
  
  P = reader.getNumPages()
  for p in range(P):
      page = reader.getPage(p)
      contents = page.getContents()
      bdata = contents.getData()
      ddata = bdata.decode('utf-8') #decoded data (string)  
      for key in replacements.keys():
          ddata = ddata.replace(key, replacements[key])
      
      contents.setData(ddata.encode('utf-8')) #Error occurs here
      
      #page.setContents(contents)
      writer.addPage(page)
  
  with open(&quot;result.pdf&quot;, 'wb') as f:
      writer.write(f)
  </code></pre>
  <p>The problem is that <code>contents.setData</code> raises <code>PdfReadError: Creating EncodedStreamObject is not currently supported</code>.</p>
  <p>Can anybody think of a workaround?</p>
  <p>P.S. Applying the method described <a href="https://stackoverflow.com/questions/41769120/search-and-replace-for-text-within-a-pdf-in-python">here</a> did create a new PDF file but without replacements.</p>