SHARE
TWEET

Untitled

a guest Jun 15th, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #requirements.txt
  2. xhtml2pdf
  3. mimerender
  4.  
  5. #-----
  6. #controller.py
  7. from app.main.util import report_helper
  8.  
  9. @api.route('/pdf')
  10. class PdfGenerate(Resource):
  11.     @api.doc('generate a pdf')
  12.     def get(self):
  13.         """
  14.         Generate a PDF from an html template file using jinja2 and xhtml2pdf
  15.         :return: Generated PDF
  16.         """
  17.  
  18.         html = report_helper.generate_report()
  19.  
  20.         resp = Response(html.getvalue())
  21.         resp.headers['Content-Type'] = 'application/pdf'
  22.         resp.headers['Content-Disposition'] = 'inline; filename=export.pdf'
  23.  
  24.         html.close()
  25.  
  26.         return resp
  27.  
  28. #------
  29. #report_helper.py
  30.  
  31. import jinja2
  32. from xhtml2pdf import pisa
  33. from io import StringIO, BytesIO
  34.  
  35.  
  36. def create_pdf(data):
  37.     pdf = BytesIO()
  38.     pisa.pisaDocument(StringIO(data), pdf)
  39.     return pdf
  40.  
  41.  
  42. def generate_report():
  43.     return create_pdf(
  44.         render_template('report.html')
  45.     )
  46.  
  47.  
  48. def render_template(name):
  49.     template_loader = jinja2.FileSystemLoader(searchpath='./app/main/util/')
  50.     template_env = jinja2.Environment(loader=template_loader)
  51.     template = template_env.get_template(name)
  52.     output_text = template.render(
  53.         start_date='Mon 03 May',
  54.         end_date='Mon 10 May',
  55.         user='Jeff'
  56.     )
  57.  
  58.     return output_text
  59.  
  60. #------
  61. #report.html
  62. <html>
  63.     <head>
  64.     </head>
  65.     <body>
  66.     {% block body %}
  67.         <h2>Some page title.</h2>
  68.         <table width="100%" cellpadding="4" cellspacing="0">
  69.             <tbody>
  70.                 <tr>
  71.                     <td width="100%">Some text.</td>
  72.                 </tr>
  73.             </tbody>
  74.             <tbody>
  75.                 <tr style="border: 1px solid #000000;">
  76.                     <td width="100%">
  77.                         <h3 style="text-align: center;">Some subtitle</h3>
  78.                         <div>{{ user }}</div>
  79.                         <div>{{ start_date }} - {{ end_date }}</div>
  80.                     </td>
  81.                 </tr>
  82.             </tbody>
  83.         </table>
  84.         <hr style="margin: 3em 0;"/>
  85.     {% endblock %}
  86.     </body>
  87. </html>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top