Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Base64 to PDF file fails

I’m trying to write a Base64 string to a PDF file. But the PDF file is corrupt.
The Base64 is coming from a webrequest.

I have tried this:

blob = js_response.get("result")
with open("test.txt, "w") as txtfile:
    txtfile.write(blob)
with open("test.pdf", "w") as pdffile:
    pdffile.write(blob)

The reason I write it to a TXT file first is for debugging. The code does write 2 files:
When I open the TXT file and test it on a base64 to PDF converter like base64.guru, the right PDF file is opened.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But when I try to open the PDF file, the file is corrupt.

The most odd thing is, this exact same code was working last week. So I don’t think it has something to do with the write command, but more on the format of the Base64?

Thanks for any insights

>Solution :

Try like this

import base64

blob = js_response.get("result")

# Decode the base64 string to binary data
pdf_binary = base64.b64decode(blob)

# Write binary data to a PDF file
with open("test.pdf", "wb") as pdffile:
    pdffile.write(pdf_binary)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading