Как в следующем примере, установите каталог проекта следующим образом:
введите описание изображения здесь
это код для 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>
или вы можете просто использовать такой код:
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')