如何在Flask应用程序中将样式表文件链接到pdfkit?

时间:2016-12-01 15:31:06

标签: python pdf flask wkhtmltopdf pdfkit

我正在尝试使用pdfkit应用程序中的Flask从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输出格式错误是非常不受欢迎的。

3 个答案:

答案 0 :(得分:0)

假设您的应用程序具有config.py文件,则可以添加此配置值。

ABS_PATH_STATIC_FOLDER = "var/www/.." #here is an absolute path to static dir

然后通过以下方式指定css文件:

css = os.path.join(app.config['ABS_PATH_STATIC_FOLDER'], 'pdfstyle.css')

如果将css文件放置在静态文件夹或任何其他文件夹中,这将起作用

然后将CSS从字符串函数传递到pdfkit

pdfkit.from_string(page, 'pdfs/file.pdf', css=css)

答案 1 :(得分:-1)

单个CSS文件

css = 'example.css'
pdfkit.from_file('file.html', css=css)

多个CSS文件

css = ['example.css', 'example2.css']
pdfkit.from_file('file.html', css=css)

在你的情况下试试这个:

css = "static/style.css"
page = flask.render_template('base.html')
pdfkit.from_string(page, 'pdfs/file.pdf', css=css)
return page

答案 2 :(得分:-1)

您的代码会生成wkhtmltopdf尝试以常规文件打开的链接:

{{ url_for('static', filename='style.css') }}

变为

/static/style.css

wkhtmltopdf将在

寻找
file://static/style.css

相反,添加_external=True标志以将其指向服务器上的文件:

{{ url_for('static', filename='style.css', _external=True) }}

结果(类似)

http://localhost:5000/static/style.css