Flask is a micro - framework for Python that allows developers to build web applications quickly and easily. It provides a simple way to handle HTTP requests and responses, making it suitable for creating web - based PDF report generators.
There are several Python libraries available for generating PDFs, but two popular ones are ReportLab
and WeasyPrint
.
To start creating PDF reports in Flask, you need to install the necessary libraries. If you choose ReportLab
, you can install it using pip
:
pip install reportlab
If you prefer WeasyPrint
, you need to install both the Python library and some system dependencies. On Ubuntu, you can install the system dependencies first:
sudo apt-get install python3-dev libpango1.0-dev
Then install the Python library:
pip install weasyprint
from flask import Flask, make_response
from reportlab.pdfgen import canvas
import io
app = Flask(__name__)
@app.route('/reportlab_pdf')
def generate_reportlab_pdf():
# Create an in - memory buffer for the PDF
buffer = io.BytesIO()
# Create a new PDF object
p = canvas.Canvas(buffer)
# Add some text to the PDF
p.drawString(100, 750, "Hello, this is a PDF report generated using ReportLab in Flask!")
# Save the PDF
p.save()
# Move the buffer's pointer to the beginning
buffer.seek(0)
# Create a response object
response = make_response(buffer.getvalue())
response.headers['Content-Disposition'] = 'attachment; filename=reportlab_report.pdf'
response.mimetype = 'application/pdf'
return response
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask, make_response, render_template_string
from weasyprint import HTML
app = Flask(__name__)
@app.route('/weasyprint_pdf')
def generate_weasyprint_pdf():
# HTML template for the report
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WeasyPrint Report</title>
</head>
<body>
<h1>Hello, this is a PDF report generated using WeasyPrint in Flask!</h1>
</body>
</html>
"""
# Render the HTML template
html = render_template_string(html_template)
# Create a PDF from the HTML
pdf = HTML(string=html).write_pdf()
# Create a response object
response = make_response(pdf)
response.headers['Content-Disposition'] = 'attachment; filename=weasyprint_report.pdf'
response.mimetype = 'application/pdf'
return response
if __name__ == '__main__':
app.run(debug=True)
WeasyPrint
, font rendering and encoding issues can occur, especially if the required fonts are not installed on the server.Creating PDF reports in Flask is a valuable skill for web developers. By understanding the core concepts, typical usage scenarios, and avoiding common pitfalls, you can generate high - quality PDF reports efficiently. Whether you choose ReportLab
for programmatic PDF generation or WeasyPrint
for converting HTML to PDF, Flask provides a flexible and easy - to - use environment for this task.