Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create PDF file from from API

I have an API that returns PDF file data, and want to know how to save that data to a file.

This is a snippet of how the data looks like:

%PDF-1.4
%äüöß
2 0 obj
<</Length 3 0 R/Filter/FlateDecode>>
stream
x�=��
1E����v���0�~��� 

I tried to base64 encode and decode it but then the PDF came out blank and tried to convert the data to bytes to write to the file, but still won’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I unsuccessfully tried:

data = format(response.text,'b') with open('test.pdf', 'wb') as f: f.write(data)

and also this:

data = base64.b64encode(response.text) with open('test.pdf', 'wb') as f: f.write(data)

>Solution :

From your comments, you have said that you are using response.text to save the PDF to a file. This pre-converts the response stream to a text response, and so what you are seeing there is not quite the right result for downloading a binary file.

If you change this instead to the following, your PDF should be saved with the correct binary content:

with open('test.pdf', 'wb') as f: 
    f.write(response.content) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading