'Decode zip/base64 file as a PDF file in response in Python (Django), why my PDF is blank?
I have zip/base64 data string. First, I tried to use base64 decode it. Then used zipfile in Python to unzip this file.
Then I put contents in response as a PDF file. I can see that the PDF I downloaded has 7 pages and length is about 75000. But all pages are blank. I wonder there is something wrong with decoding?
This .decode(errors='ignore') was from another stackoverflow post. Without this statement, I cannot decode the whole thing. It will pop error like "'utf-8' codec can't decode byte 0xfe in position 28".
Here is my code:
decoded = base64.b64decode(data) // data is "zip/base64" type
with zipfile.ZipFile(io.BytesIO(decoded)) as zf:
for name in zf.namelist():
with zf.open(name) as f:
contents = f.read().decode(errors='ignore')
response = HttpResponse(
contents, content_type="application/pdf"
)
response["Content-Disposition"] = 'attachment; filename="{}"'.format(
report_name + ".pdf"
)
return response
Solution 1:[1]
You shouldn't try to decode the file contents, since it's not text. f.read() returns a bytestring, which HttpResponse will accept perfectly fine for the page content.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yut23 |
