Я пытался создать PDF-документ из конечной точки Flask, который в основном извлекает значения из базы данных MySql и показывает их на HTML-странице. Я пробовал jsPDF, но не смог получить результат
Вот мой код Python:
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()
Ниже приведены html-страницы: 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>
и, наконец, страница, на которой я хочу создать PDF-файл и загрузить его простым щелчком мыши, используя 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>