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.
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)