How to link stylesheet files to pdfkit in Flask application?
Single CSS file
css = 'example.css'pdfkit.from_file('file.html', css=css)
Multiple CSS files
css = ['example.css', 'example2.css']pdfkit.from_file('file.html', css=css)
In your case try this:
css = "static/style.css"page = flask.render_template('base.html')pdfkit.from_string(page, 'pdfs/file.pdf', css=css)return page
Your code results in a link that wkhtmltopdf tries to open as a regular file:
{{ url_for('static', filename='style.css') }}
becomes
/static/style.css
which wkhtmltopdf will look for at
file://static/style.css
Instead, add the _external=True
flag to point it towards the file on the server:
{{ url_for('static', filename='style.css', _external=True) }}
results in (something like)
http://localhost:5000/static/style.css
Assuming your app has config.py file you can add this config value.
ABS_PATH_STATIC_FOLDER = "var/www/.." #here is an absolute path to static dir
Then specify css file by:
css = os.path.join(app.config['ABS_PATH_STATIC_FOLDER'], 'pdfstyle.css')
This will work if the css file is placed in static folder or any other folder
Then pass on css to pdfkit fromstring function
pdfkit.from_string(page, 'pdfs/file.pdf', css=css)