How can I pass a string of bytes to PDF with Python?

2

I am connecting to an API in which you return a PDF in bytes format and I want to know if there is any simple way to format it in PDF to be able to download it.

My problem is that it returns a string of data 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 discovered that is a PDF file in bytes.

I try to save it in a file and store it on my computer but it does not return anything and it does not save anything.

arraybytes = bytearray(sticker.bytesReport)
fichero = open("prueba.txt", "wb")
pdf.write(fichero)
pdf.close()
    
asked by F Delgado 22.02.2018 в 08:38
source

1 answer

1

Suppose that the variable resultado contains the string of bytes returned by the server, for example:

resultado = b'%PDF-1.1\n%\xc2\xa5\xc2\xb1\xc3\xab\n1 0 obj\n<< /Type /Catalog\n/Pages 2 0 R\n>>\nendobj\n2 0 obj\n<< /Type /Pages\n/Kids [3 0 R]\n/Count 1\n/MediaBox [0 0 300 144]\n>>\nendobj\n3 0 obj\n<<  /Type /Page\n/Parent 2 0 R\n/Resources\n<< /Font\n<< /F1\n<< /Type /Font\n/Subtype /Type1\n/BaseFont /Times-Roman\n>>\n>>\n>>\n/Contents 4 0 R\n>>\nendobj\n4 0 obj\n<< /Length 55 >>\nstream\nBT\n/F1 18 Tf\n0 0 Td\n(Hello World) Tj\nET\nendstream\nendobj\nxref\n0 5\n0000000000 65535 f \n0000000018 00000 n \n0000000077 00000 n \n0000000178 00000 n \n0000000457 00000 n \ntrailer\n<<  /Root 1 0 R\n/Size 5\n>>\nstartxref\n565\n%%EOF\n'

You can dump it into a file simply like this:

with open("fichero.pdf", "wb") as f:
   f.write(resultado)

In the example I have put, the resulting file is a valid pdf that when opened will show:

    
answered by 22.02.2018 / 10:40
source