Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. def print_pdf():
  2. from string import Template
  3. from xhtml2pdf.pisa import CreatePDF
  4.  
  5. from io import BytesIO
  6.  
  7. html = """
  8. <!DOCTYPE html>
  9. <html lang="en">
  10. <head>
  11. <meta charset="UTF-8">
  12. <title>Django HTMLtoPDF Tutorial</title>
  13. </head>
  14. <body>
  15. <h1>HTML To PDF</h1>
  16. <b>I'm building web-based, data-driven apps using Django. <br>
  17. Eventually (or unfortunately), I will need to generate some reports that are printer-friendly. <b>
  18. Logically, PDF is the format for such files... <br>
  19. so how am I going to convert my xHTML and CSS to a nice-looking PDF document?<br>
  20.  
  21. The Django Book has a whole chapter dedicated to Generating Non-HTML Content.<br>
  22. They seem to to be fond of ReportLab ToolKit.<br>
  23. The caveat here, though, is that you need to know a bit about the internals of a PDF document.<br>
  24. If you're familiar with this, the ReportLab toolkit seems to be the way to go! It has many features, and it seems to be a powerful PDF-generating tool.
  25. </b>
  26. </body>
  27. </html>
  28.  
  29.  
  30. """
  31.  
  32. response.headers['Content-Type'] = 'application/pdf'
  33.  
  34. in_mem_stream = BytesIO() # type: BytesIO
  35. CreatePDF(html, dest=in_mem_stream)
  36. pdf = in_mem_stream.getvalue() # type: bytes
  37. in_mem_stream.close()
  38.  
  39. return pdf
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement