How to link stylesheet files to pdfkit in Flask application?

你说的曾经没有我的故事 提交于 2019-12-04 18:11:44

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)

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!