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

raf reportlab at raf.org
Mon Feb 24 23:04:23 EST 2025


Never mind. I patched my version which seemed OK, but
it wasn't. I got lots of absurd warnings about files
left open that made no sense. I had some StringIO
objects in my code that I was passing to reportlab
somehow. Now I've changed them to BytesIO objects
and things are looking good again.

cheers,
raf

On Tue, Feb 25, 2025 at 01:55:59PM +1100, raf via reportlab-users <reportlab-users at lists2.reportlab.com> wrote:

> 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
> 
> _______________________________________________
> reportlab-users mailing list
> reportlab-users at lists2.reportlab.com
> https://pairlist2.pair.net/mailman/listinfo/reportlab-users


More information about the reportlab-users mailing list