8

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.

phicon
  • 3,549
  • 5
  • 32
  • 62
  • Where does `printname` come from? – Kevin Christopher Henry Jun 24 '15 at 22:38
  • 1
    Most likely 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('http://google.com', False) – Peter Brittain Jun 24 '15 at 23:06
  • can you post the server log from the time span when the error happens? (I know you said there isn't any error there, I just have some hunch and want to see the requests information to make sure I'm not wrong before suggesting an answer) – yuvi Jun 28 '15 at 00:04

2 Answers2

6

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.

Community
  • 1
  • 1
Himanshu Mishra
  • 8,510
  • 12
  • 37
  • 74
3

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.

Peter Brittain
  • 13,489
  • 3
  • 41
  • 57