I try to get an agreement file (ex:agreement.HTML), convert it to a PDF file and download that file to the users computer.
I want to use PDFkit module, get the html file on my webapp and download the generated pdf to the local user.
How is that possible?
Like this example below, set project directory like this: enter image description here
this the code for app.py
from flask import Flask, render_template
import pdfkit
import os
app = Flask(__name__)
app.config['PDF_FOLDER'] = 'static/pdf/'
app.config['TEMPLATE_FOLDER'] = 'templates/'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/convert')
def konversi():
htmlfile = app.config['TEMPLATE_FOLDER'] + 'index.html'
pdffile = app.config['PDF_FOLDER'] + 'demo.pdf'
pdfkit.from_file(htmlfile, pdffile)
return '''Click here to open the
<a href="http://localhost:5000/static/pdf/demo4.pdf">pdf</a>.'''
if __name__ == '__main__':
app.run(debug=True)
index.html
<html>
<head>
<title>Demo pdfkit</title>
</head>
<body>
<h2>Flask PDFKit</h2>
<table border="1">
<tr>
<th width="90">ID</th>
<th width="250">Title</th>
<th width="150">writer</th>
<th width="170">Publisher</th>
</tr>
<tr>
<td>B001</td>
<td>Learning Flask Framework</td>
<td>Matt Copperwaite</td>
<td>PACKT Publishing</td>
</tr>
<tr>
<td>B002</td>
<td>Flask By Example</td>
<td>Gareth Dwyer</td>
<td>PACKT Publishing</td>
</tr>
<tr>
<td>B003</td>
<td>Essential SQLAlchemy</td>
<td>Rick Copeland</td>
<td>OReilly</td>
</tr>
</table>
<p><a href="http://localhost:5000/convert">Convert to PDF</a></p>
</body>
</html>
or you can just use code like this:
import pdfkit
# from file
pdfkit.from_file('templates/index.html', 'demo_from_file.pdf')
# from string
pdfkit.from_string('Hello World', 'demo_from_string.pdf')
# from url
pdfkit.from_url('https://www.google.com/', 'demo_from_url.pdf')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With