Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 224
Rafael Miller Avatar asked Jan 04 '18 21:01

Rafael Miller


People also ask

How do I get files from Base64?

How to convert Base64 to file. Paste your string in the “Base64” field. Press the “Decode Base64 to File” button. Click on the filename link to download the file.

What is Base64 encoded PDF?

Base64 encoding is used to encode binary data, such as a PDF file, into an ASCII string format that is compatible with systems that can only handle text. For example, email attachments and binary uploads in HTML forms are converted and transmitted as Base64 encoded data.

Can PDF be Base64?

💻 Can I convert PDF to BASE64 on Linux, Mac OS or Android? Yes, you can use free Converter app on any operating system that has a web browser. Our PDF to BASE64 converter works online and does not require any software installation.


1 Answers

Extending @Jebby's answer using Base64 (had the same issue as @SmartManoj)

import base64
base64String = "JVBERi0xLjQKJeHp69MKMSAwIG9iago8PC9Qcm9kdWNlciAoU2tpYS9..."


with open("test.pdf", "wb") as f:
    f.write(base64.b64decode(base64string))
like image 131
Dfranc3373 Avatar answered Oct 05 '22 07:10

Dfranc3373