Welcome folks today in this blog post we will be looking on how to encode a pdf file to base 64 string
in python 3 using the core base64 module. All the source code of the application is shown below
Get Started
In order to get started you need to install base64
module of python using the pip command as shown below
pip install base64
After installing this module just make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 |
import base64 with open("sample2.pdf", "rb") as pdf_file: encoded_string = base64.b64encode(pdf_file.read()) print(encoded_string) |
Here in this block of python code as you can see in the first line we are importing base64
module and after that we are opening the local pdf file with the path and then after reading it we are converting or encoding to base64
using the b64encode
method which is available in the base64
module. Lastly we are printing the output encoded base64 string to the console
Now if you execute the python script by typing the below command in the console
python app.py
As you can see the following base64
code of the input pdf file is printed out