This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revision | |||
| python:djangoandwkhtmltopdf [d.m.Y H:i] – kodmasin | python:djangoandwkhtmltopdf [d.m.Y H:i] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ====== Generating PDF within django using wkhtmltopdf ====== | ||
| + | I need to generate some PDF reports within django. I have been looking for library for pdf printing but did not find open source (free) one with features I needed. AS I already have view which generates html I was looking for tool which can transform html to pdf. So I decide to use [[http:// | ||
| + | |||
| + | In django I have used following code for generating pdf. This could give you idea how to do it yourself. | ||
| + | |||
| + | <code python> | ||
| + | #my functions to get data and to render html | ||
| + | data = get_offer_data(id) | ||
| + | html = offer_html(request, | ||
| + | #preparing wkhtmltopdf command to run using pipes | ||
| + | # | ||
| + | # an looks like / | ||
| + | #Popen has little confusing way to accept command arguments | ||
| + | #Last two " | ||
| + | # | ||
| + | #This is how this command will look in shell | ||
| + | # > | ||
| + | wkhtml2pdf = subprocess.Popen((WKHTML2PDF_COMMAND, | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | stdin=subprocess.PIPE, | ||
| + | stdout=subprocess.PIPE) | ||
| + | wkdata = wkhtml2pdf.communicate(html.encode(' | ||
| + | pdf = wkdata[0]; | ||
| + | | ||
| + | response = HttpResponse(mimetype=' | ||
| + | response[' | ||
| + | response.write(pdf) | ||
| + | return response | ||
| + | </ | ||
| + | |||
| + | :!: If you have long tables (which are extending over more pages) be careful as they will probably be broken between pages. | ||