0

I'm using django for a small project and I would make users able to download a pdf that's already existed in media/doc/ path so I wrote this code

    with open('media/doc/document.pdf', 'r',encoding='latin1',errors='replace') as pdf:
        response = FileResponse(pdf.read(), content_type='application/pdf')
        response['Content-Disposition'] = 'inline;filename=some_file.pdf'
        return response

but when the pdf file get downloaded it's shown pages empty btw I have already tried utf-8 encoding and doesn't work for me even this doesn't work for me

So How can I make pages visible?

Dev Kim
  • 95
  • 1
  • 3
  • 9
  • are you sure this did point to your file `open('media/doc/document.pdf`? – Lemayzeur Jun 11 '18 at 01:37
  • @Lemayzeur yeah I'm, the file is already existed and it gets downloaded but it gives me empty pages btw I have tested many documents but I face the same issue – Dev Kim Jun 11 '18 at 02:07
  • 1
    try sending an `HttpResponse(pdf.read(), content_type='application/pdf')` with application/pdf as content_type. and remove all the arguments in open() like `with open('media/doc/document.pdf', 'rb') as pdf` .dont't for foreget `rb` for binary – Lemayzeur Jun 11 '18 at 02:16
  • @Lemayzeur it works for me Thank you I really appreciate your help – Dev Kim Jun 11 '18 at 07:14
  • Great! I see in your comments that you have a problem of: users will download the same pdf file, do you have it work now? – Lemayzeur Jun 11 '18 at 13:26

1 Answers1

0

The code you are trying that should work but if it is not working than i suggest that you can download pdf file with HTML code also.

<a class="btn btn-lg btn-primary" href="{{ obj.url }}" type="application/octet-stream .pdf" download="menu.pdf" target="_blank" role="button">Download a pdf file</a>

recently download attribute has added in HTML5 you can directly download file from HTML now no need to create extra view for that now. you can see details Here

Parth Modi
  • 291
  • 1
  • 5
  • Thank's for your help!! it works but I can't use it because not all users will download the same pdf file in fact I don't mention it above to avoid making things complicated btw the solution of @Lemayzeur works for me – Dev Kim Jun 11 '18 at 07:21