I am connecting to an API that returns a PDF in byte format and I want to know if there is any simple way to format it to PDF so I can download it.
My problem is that it returns a data string in this format:
b'%PDF-1.7 \n%\xe2\xe3\xcf\xd3 \n1 0 obj \n<< \n/Type /Catalog \n/Pages 2 0 R \n/PageMode /UseNone \n/ViewerPreferences << \n/FitWindow true \n/PageLayout /SinglePage \n/NonFullScreenPageMode /UseNone \n>> \n>> \nendobj \n5 0 obj \n<< \n/Length 6427 \n/Filter [ /FlateDecode ] \n>> ... '
What I have discovered is that that is a PDF file in bytes.
I try to save it to a file and store it on my computer but it doesn't return anything and it doesn't save anything.
arraybytes = bytearray(sticker.bytesReport)
fichero = open("prueba.txt", "wb")
pdf.write(fichero)
pdf.close()
Suppose that the variable
resultado
contains the string of bytes that the server has returned to you, for example this:You can dump it to a file just like this:
In the example that I have given, the resulting file is a valid pdf that, when opened, will show: