简体   繁体   中英

Generating a PDF from a flask endpoint

I was trying to make a PDF document from a Flask endpoint that basically retrieves the values from a MySql database and shows it on a HTML page. I tried jsPDF but was unable to get the result

Here is my Python code:

from flask import Flask, render_template, request
from flask_mysqldb import MySQL

app = Flask(__name__)
# configure db
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'username'
app.config['MYSQL_PASSWORD'] = 'dbpassword'
app.config['MYSQL_DB'] = 'flaskapp'
mysql = MySQL(app)
@app.route('/', methods=['GET', 'POST'])
def alpha():
    if request.method == 'POST':
        # Fetch the form data
        userDetails = request.form
        name = userDetails['name']
        email = userDetails['email']
        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO users(name,email) VALUES(%s,%s)", (name, email))
        mysql.connection.autocommit(on=True)
        cur.close()
        return 'success'

    return render_template('index.html')

@app.route('/users')
def users():
    cur = mysql.connection.cursor()
    resultValue = cur.execute("SELECT * from users")
    if resultValue > 0:
        userDetails = cur.fetchall()
        return render_template('users.html', userDetails=userDetails)


@app.route('/showpdf')
def showpdf():
    return render_template('showpdf.html')



if __name__ == '__main__':
    app.run()

Below are the html pages: users.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Display Records From DB</title>

</head>
<body>
<style>
    th {
        background-color: orange;
    }
</style>
<table border="1">
    <tr>
        <th>
            Name
        </th>
        <th>
            Email Id
        </th>
    </tr>
    {% for users in userDetails %}
    <tr>
        <td>{{users[0]}}</td>
        <td>{{users[1]}}</td>
    </tr>
    {% endfor %}
</table>
</body>
</html>

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DB Adder</title>
</head>
<body>
<form method="POST" action="">
    Name <input type="text" name="name"/>
    <br>
    Email <input type="email" name="email"/>
    <br>
    <input type="submit">

</form>
</body>
</html>

and finally the Page where i want to generate a pdf and download it by a simple click using jsPDF showpdf.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PDF PAGE</title>
    <script type="text/javascript" src="/jspdf.min.js"></script>
    <script>
        function genPDF(){
        var doc = new jsPDF();
        doc.text(20,20,'Here is the pdf from the endpoint : localhost:5000/showpdf');
        doc.addPage();
        doc.save('localhost:5000/users');

        }
    </script>
</head>
<body>
<h1>This page will output a pdf using jsPDF</h1>
<a href="javascript:genPDF()">Click To Download PDF</a>
</body>
</html>

I think you have misunderstood the backend which is flask and the front end which is html and javascript.

When you click the <a> tag , the browser will send your request to the backed which is the flask, but you haven't any pdf doc in your file system. That's why you got the 404 error.

May be you can generate the pdf in the front end(I am not familiar with the jsPDf library). At least do the follow thing:

  • write a function or something others, that could generate pdf using js.

  • Put a button or something else in your showpdf.html ,when user click the button,there is a event , use step 1 function as the event listener, then generate the pdf for the user.

You can use flask_weasyprint :

from flask_weasyprint import HTML, render_pdf
import flask
app = flask.Flask(__name__)
@app.route('/users')
def users():
  cur = mysql.connection.cursor()
  resultValue = cur.execute("SELECT * from users")
  if resultValue > 0:
    userDetails = cur.fetchall()
    html = render_template('users.html', userDetails=userDetails)
    return render_pdf(HTML(string=html))

Now, once the user navigates to /users , the download will start.

based on Ajax1234 solutions and issues you are having..

Your problem is that flask could not locate where flask_weasyprint is installed.

If you are on windows, you have to navigate to /script directory to install hence

cd C:\flaskproject\flask\Scripts

C:\flaskproject\flask\Scripts>pip install Flask-WeasyPrint

Then when you run your application. everything will work fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM