Python Django PDFKIT - [Errno 9] Bad file descriptor

1.6k views Asked by At

I use pdfkit and wkhtmltopdf to generate pdf documents. When i generate the first pdf all is well. When i quickly (within 5 seconds) generate an other i get the error [Errno 9] Bad file descriptor. If i close the error (step back in browser) and open again, it will create the pdf.

my views.py

config = pdfkit.configuration(wkhtmltopdf='C:/wkhtmltopdf/bin/wkhtmltopdf.exe')
pdfgen = pdfkit.from_url(url, printname, configuration=config)
pdf = open(printname, 'rb')

response = HttpResponse(pdf.read())
response['Content-Type'] = 'application/pdf'
response['Content-disposition'] = 'attachment ; filename =' + filename
pdf.close()
return response

Maybe important note: i run this site on IIS8, when running from commandline (python manage.py runserver) the error is not present.

Any guidelines on how to handle this error would be great.

2

There are 2 answers

0
Himanshu Mishra On BEST ANSWER

When i quickly (within 5 seconds) generate an other

This point suggests that your code is flawless and the problem lies with your browser rejecting the URL as Peter suggests.

Most probably the cause of the error lies with file buffer flush. Consider flushing buffer at appropriate places.

0
Peter Brittain On

With no further information forth-coming, I'll convert my comment to an answer...

Most likely the issues are that your URL is being rejected by the web server when you try the quick reload (via from_url) or that you are having problems accessing the local file you are trying to create.

You could try to eliminate the latter by just writing straight to a variable by passing False as your output file name - e.g. pdf = pdfkit.from_url('google.com', False).

If that doesn't solve it, your issue is almost certainly with the server rejecting the URL - and so you need to look at the diagnostics on that server.