How to convert a PDF from base64 string to a file?

Rafael Miller picture Rafael Miller · Jan 4, 2018 · Viewed 13.1k times · Source

I have a PDF as a base64 string and I need to write it to file using Python. I tried this:

import base64

base64String = "data:application/pdf;base64,JVBERi0xLjQKJeHp69MKMSAwIG9iago8PC9Qcm9kdWNlciAoU2tpYS9..."

with open('temp.pdf', 'wb') as theFile:
  theFile.write(base64.b64decode(base64String))

But it didn't create a valid PDF file. What am I missing?

Answer

Mark picture Mark · Jan 4, 2018

From my understanding base64decode only takes in a base64 string and looks like you have some headers on your string that are not encoded.

I would remove "data:application/pdf;base64,"

check out the doc here: https://docs.python.org/2/library/base64.html

When I've used it in the past, I have only used the encoded string.