Transform a base 64 encoded string into a downloadable pdf using django rest framework
<p>I have a django/python3 application that requests the Limesurvey API and gets a base 64 encoded string as result.
I'd like to return this result as a downloadable pdf file.</p>

<p>Here's my current implementation that's simply display the base 64 string into a blank page...</p>

<pre><code>    data = limesurvey.export_responses_by_token(survey_id, token)
    response = HttpResponse(data, content_type='application/pdf')
    return StreamingHttpResponse(response)
</code></pre>

<p>Any help would be very appreciated!</p>

<p>Three steps:</p>

<h2>Dump your base64 content into StringIO</h2>

<pre><code>import cStringIO as StringIO
buffer = StringIO.StringIO()
content.decode('base64')
buffer.write(content)
</code></pre>

<h2>Send response with proper header</h2>

<pre><code>from django.http import HttpResponse
from wsgiref.util import FileWrapper

# generate the file
response = HttpResponse(FileWrapper(buffer.getvalue()), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=MY_FILE_NAME.zip'
return response
</code></pre>

<h2>Configure your server</h2>

<p>Beyond the scope of django. </p>

<p>e.g. for nginx, refer to <a href="https://tn123.org/mod_xsendfile/" rel="nofollow">this link</a></p>

<h2>Update</h2>

<p>After testing your content in some <a href="https://www.base64decode.org/" rel="nofollow">online converter</a>, I'm sure that's base64 stuff.</p>

<p>However, the reason why it doesn't work remains unknown until further information is provided.</p>

<p>My mock snippet is like this.</p>

<pre><code>&gt;&gt;&gt; test_str = 'test'
&gt;&gt;&gt; base_64 = test_str.encode('base64')
&gt;&gt;&gt; base_64.decode('base64')
'test'
&gt;&gt;&gt; base_64
'dGVzdA==\n'
</code></pre>

python django python-3.x django-rest-framework