main.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import pymysql
  2. from app import app
  3. from db import mysql
  4. from flask import Flask, Response, render_template
  5. @app.route('/')
  6. def upload_form():
  7. return render_template('download.html')
  8. @app.route('/download/report/pdf')
  9. def download_report():
  10. conn = None
  11. cursor = None
  12. try:
  13. conn = mysql.connect()
  14. cursor = conn.cursor(pymysql.cursors.DictCursor)
  15. cursor.execute("SELECT emp_id, emp_first_name, emp_last_name, emp_designation FROM employee")
  16. result = cursor.fetchall()
  17. pdf = FPDF()
  18. pdf.add_page()
  19. page_width = pdf.w - 2 * pdf.l_margin
  20. pdf.set_font('Times','B',14.0)
  21. pdf.cell(page_width, 0.0, 'Employee Data', align='C')
  22. pdf.ln(10)
  23. pdf.set_font('Courier', '', 12)
  24. col_width = page_width/4
  25. pdf.ln(1)
  26. th = pdf.font_size
  27. for row in result:
  28. pdf.cell(col_width, th, str(row['emp_id']), border=1)
  29. pdf.cell(col_width, th, row['emp_first_name'], border=1)
  30. pdf.cell(col_width, th, row['emp_last_name'], border=1)
  31. pdf.cell(col_width, th, row['emp_designation'], border=1)
  32. pdf.ln(th)
  33. pdf.ln(10)
  34. pdf.set_font('Times','',10.0)
  35. pdf.cell(page_width, 0.0, '- end of report -', align='C')
  36. return Response(pdf.output(dest='S').encode('latin-1'), mimetype='application/pdf', headers={'Content-Disposition':'attachment;filename=employee_report.pdf'})
  37. except Exception as e:
  38. print(e)
  39. finally:
  40. cursor.close()
  41. conn.close()
  42. if __name__ == "__main__":
  43. app.run()