[reportlab-users] Please help with error in pdfbase/pdfdoc.py (TypeError: string argument expected, got 'bytes')

raf reportlab at raf.org
Mon Feb 24 21:55:59 EST 2025


Hi,

macos-10.14 (old), python-3.12 (via macports), reportlab-4.3.1 (via pip)

I'm converting some python2 code that uses reportlab-3.3.0
to python3 (with reportlab 4.3.1) and I'm encountering the
following error:

  Traceback (most recent call last):
    File "/Users/raf/src/aps.py3/lib/./report.py", line 6196, in test_pdf_basefont
      report_pdf = report.pdf()
                 ^^^^^^^^^^^^
    File "/Users/raf/src/aps.py3/lib/./report.py", line 1844, in pdf
      self._pdf.save()
    File "/opt/local/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/reportlab/pdfgen/canvas.py", line 1301, in save
      self._doc.SaveToFile(self._filename, self)
    File "/opt/local/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/reportlab/pdfbase/pdfdoc.py", line 215, in SaveToFile
      f.write(data)
  TypeError: string argument expected, got 'bytes'

The context of the f.write(data) file is:

  data = self.GetPDFData(canvas)
  if isUnicode(data):
      data = data.encode('latin1')
  f.write(data)

So data is explictly converted from str to bytes, but
https://docs.python.org/3/tutorial/inputoutput.html
says:

  f.write(string) writes the contents of string to the
  file, returning the number of characters written.

This looks like a bug that would always be triggered
every time this code is run, but that seems unlikely.
It looks like the above code should be:

  data = self.GetPDFData(canvas)
  if not isUnicode(data):
      data = data.decode('latin1')
  f.write(data)

or even:

  data = self.GetPDFData(canvas)
  if not isUnicode(data):
      data = data.decode('utf8')
  f.write(data)

What are your thoughts? Is this a bug in reportlab?
If so, can it be fixed?
If not, what might I have done to cause this?

Many thanks in advance,
raf



More information about the reportlab-users mailing list