【发布时间】:2017-04-16 07:43:12
【问题描述】:
我正在尝试在 Flask 应用程序中使用 pdfkit 从 html 页面创建 pdf,但是在使用 pdfkit 时我无法加载静态文件(样式表)。
我试图提出最小的例子。我有这个文件结构
App
|_ static
| |- style.css
|_ templates
| |- base.html
|_ pdfs
| |- file.pdf
|_ application.py
内部application.py:
import flask
import pdfkit
app = flask.Flask(__name__)
@app.route('/')
def index():
page = flask.render_template('base.html')
pdfkit.from_string(page, 'pdfs/file.pdf')
return page
@app.route('/download', methods=['POST'])
def download():
if flask.request.method == 'POST':
flask.send_from_directory(
directory='pdfs', filename='file.pdf', as_attachment=True)
else:
flask.redirect(flaks.url_for('index'))
if __name__ == '__main__':
app.run()
样式表只是为 td 元素添加了红色背景:
td {
background-color: red;
}
最后是base.html:
<!DOCTYPE html>
<html>
<head>
<title>Test App</title>
<link href={{ url_for('static', filename='style.css') }} rel='stylesheet'>
</head>
<body>
<div id='to_pdf'>
<table>
<tr>
<th>Firstname</th>
</tr>
<tr>
<td>Jill</td>
</tr>
<tr>
<td>Eve</td>
</tr>
</table>
<form action='/download' method='POST'>
<button type="submit" value="Print" />PRINT</form>
</form>
</div>
</body>
</html>
对不起,代码负载,但它实际上是非常基本的。 我想要的只是有一个按钮,一旦点击它就会下载一个pdf文件(这个pdf是html文件转换为pdf。
它有点工作,但控制台输出如下:
Loading pages (1/6)
Warning: Failed to load file:///static/style.css (ignore)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
问题
pdfkit,它基本上调用了wkhtmltopdf,在static 文件夹中找不到样式表文件。我遇到这个问题的应用程序更健壮,使用了 boostrap 等,并且 pdf 输出格式错误是非常不可取的..
【问题讨论】:
标签: python pdf flask wkhtmltopdf pdfkit