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.
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)