Search code examples
pythonpdfbase64file-writing

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


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?


Solution

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