how to use python pdfkit with python flask webapp how to use python pdfkit with python flask webapp flask flask

how to use python pdfkit with python flask webapp


Like this example below, set project directory like this:enter image description here

this the code for app.py

from flask import Flask, render_templateimport pdfkitimport osapp = 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 filepdfkit.from_file('templates/index.html', 'demo_from_file.pdf')# from stringpdfkit.from_string('Hello World', 'demo_from_string.pdf')# from urlpdfkit.from_url('https://www.google.com/', 'demo_from_url.pdf')