How to export data in pdf format in flask

This article explains how to export (download) data in a pdf file using the template. For this, we have to use the xhtml2pdf package to export pdf.

To export data in pdf format we have to create a new file that contains the data and design and layout of the pdf.

So first we have to install the xhtml2pdf package - 

 > pip install xhtml2pdf
After this, you have to create a download link for the download of the pdf file. For this, we have to create an HTML file in our template directory.

template/export-pdf.html
<!DOCTYPE html>
<html>
<head>
<title>Export PDF</title>
</head>
<body>
<a href="/exportpdf">Export PDF </a>
</body>
</html>
After this template, we have to configure MySQL settings and create a function to fetch data. So let's set up the database configuration and routing, we have to create a new file with the name views.py

from flask import Flask,make_response
from io import BytesIO, StringIO
from flask_mysqldb import MySQL
import MySQLdb.cursors

app = Flask(__name__)

# Database Configrations
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'flask_product_mst'

# intialize mysql
mysql = MySQL(app)

def mysqlCursor():
    mysql_cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    return mysql_cursor

    
def fetchAll():
    
    query = f"SELECT * FROM {product}"
    mysql_cursor = mysqlCursor()
    mysql_cursor.execute(query)
    rows = mysql_cursor.fetchall()
    if rows:
        return rows
    return False


@app.route('/exportpdf')
def exportpdf():
    products = fetchAll()
    html = render_template('product_export_template.html', products=products)
    pdf = BytesIO()
    pisa.CreatePDF(BytesIO(html.encode('utf-8')), pdf)
    response = make_response(pdf.getvalue())
    response.headers['Content-Type'] = 'application/pdf'
    response.headers['Content-Disposition'] = 'attachment; filename=product.pdf'
    return response
After all the implementation, we have to run our application with the run command, So let's run the application
> flask --app views run

Comments

Post a Comment