Convert Base64 to PDF in Python: Working Decode Example
Convert Base64 to PDF in Python using the standard library. Includes clean decode examples, validation tips, and API-response handling.
Python is one of the easiest environments for Base64→PDF work because the standard library already includes what you need. In most cases, the entire job is: strip any data URI prefix, decode the bytes, and write the output in binary mode.
TL;DR: Use
base64.b64decode()on the cleaned string, then write the result withopen(..., 'wb').
Minimal example
import base64
def base64_to_pdf(base64_string: str, output_path: str) -> None:
clean_base64 = base64_string.split(',')[-1]
pdf_bytes = base64.b64decode(clean_base64)
with open(output_path, 'wb') as f:
f.write(pdf_bytes)
Usage
base64_to_pdf(base64_value, 'invoice.pdf')
Working with API JSON responses
import base64
import requests
response = requests.get('https://api.example.com/documents/123')
payload = response.json()
pdf_bytes = base64.b64decode(payload['data'])
with open(payload['fileName'], 'wb') as f:
f.write(pdf_bytes)
Validate before writing
import base64
def is_valid_base64(value: str) -> bool:
try:
base64.b64decode(value.split(',')[-1], validate=True)
return True
except Exception:
return False
This is worth doing when the input comes from users or third-party systems.
Common mistakes
Opening the file in text mode
Always use 'wb', not 'w'. PDFs are binary files.
Forgetting the data URI prefix
If the value looks like this:
data:application/pdf;base64,JVBERi0xLjQK...
split on the first comma or just take the last segment like the examples above.
The decoded file is not a PDF
That usually means the wrong field was decoded or the source system mislabeled the content.
When Python is the best fit
Choose Python when:
- you are processing documents in batch jobs
- the file comes from APIs, queues, or ETL scripts
- you need validation and filesystem control
- this is backend automation, not a UI feature
For quick manual work, GoGood.dev Base64 Converter is still the fastest sanity check.
FAQ
Can Python decode Base64 to PDF without extra libraries?
Yes. The built-in base64 module is enough.
Why is my PDF unreadable after decoding?
Most likely the input string is incomplete, malformed, or not really PDF data.
Should I validate the string first?
Yes, especially for user-submitted or third-party payloads.
Python makes this workflow boring in a good way. Clean the input, decode it, write bytes to disk, and move on. If you only need to inspect one file quickly, use GoGood.dev Base64 Converter before writing any script.
Related: How to Convert Base64 to PDF Online · How to Convert Base64 Back to a File · Why Your Base64 PDF Is Corrupted · How to Convert an Image to Base64 · When to Use Base64