Pythondex
Python Conversion Programs

Convert Base64 To PDF In Python

Last updated January 31, 2024 by Jarvis Silva

In this tutorial we will see how to convert base64 to pdf using python, base64 is used to encode binary data so inorder to convert base64 to pdf we will use the python library Base64, it will allows us to decode base64.

Python Code To Convert Base64 To PDF


import base64

b64 = 'enter base64 code here'

bytes = base64.b64decode(b64, validate=True)

f = open('sample.pdf', 'wb')
f.write(bytes)
f.close()

Above is the python code for converting base64 to pdf, let’s see how this code works:

  • The code imports the base64 module for working with Base64 encoding and decoding.
  • There is a variable named b64 which should contain the Base64-encoded string you want to decode.
  • The code uses base64.b64decode() to decode the Base64 string and stores the result in the bytes variable.
  • It opens a file named sample.pdf in write-binary mode (‘wb’) using open().
  • The decoded binary data is written to the file using f.write(bytes).
  • Finally, the file is closed using f.close().

After running the program you will see that it printed the base64 version of the pdf file so now if you want to convert it back to base64 then refer this tutorial: Convert pdf to base64 in python.

Here are some more python programs you will find helpful:

I hope you found what you were looking for from this python tutorial, and if you want more python tutorials like this, do join our Telegram channel to get updated.

Thanks for reading, have a nice day 🙂