Convert Base64 to PDF in Python

Hello friends, you know how to convert a string to base64 using pybase64 module. In this tutorial, I will tell you how you can convert a base64 string to PDF in Python.

Convert Base64 to PDF in Python

Firstly, I have imported pybase64 package to my code. I have then defined a variable encoded_str, which holds the value of an encoded string in byte form. Using the b64decode() function I have decoded the string. The latter function takes the encoded string in byte format as an argument. I have stored the decoded string in byte format in a temporary variable, file_decoded. To obtain the decoded string in string format, I have used the decode() function with 'ascii' as an argument, and stored the result in a variable, file_str.

Code :

import pybase64

encoded_str = b"Q29kZXNwZWVkeSBpcyBmdW4u"

file_decoded = pybase64.b64decode(encoded_str)
file_str = file_decoded.decode('ascii')
print(file_decoded)
print(type(file_decoded))
print(file_str)
print(type(file_str))

Output :

b'Codespeedy is fun.'
<class 'bytes'>
Codespeedy is fun.
<class 'str'>

Once decoded, I want to write this string on a PDF file. To create a PDF I have used the fpdf package. You can check out my tutorial on creating a PDF using fpdf in Python to know more.

Code :

from fpdf import FPDF

pdf_file = FPDF()
pdf_file.add_page()
pdf_file.set_font("Arial", size = 15)
pdf_file.cell(200, 10, txt = file_str, ln = 1)
pdf_file.output("sample_decode.pdf")

It will create a pdf file named sample_decode.pdf

To write the decoded string, I used the cell() function and defined txt attribute as file_str. It is important to note, that if you try writing the decoded string in byte format on the PDF using this method it will throw an Exception. I have used the output() function to create a PDF with the name sample_decode.pdf.

Thus you can now convert Base64 to PDF in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *