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

qua*_*pka 2 python pdf pdfkit wkhtmltopdf flask

我正在尝试使用pdfkit内部Flask应用程序从 html 页面创建 pdf,但是在使用pdfkit.

我试图举出最小的例子。我有这个文件结构

App
 |_ static
 |  |- style.css
 |_ templates
 |  |- base.html
 |_ pdfs
 |  |- file.pdf
 |_ application.py
Run Code Online (Sandbox Code Playgroud)

里面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()
Run Code Online (Sandbox Code Playgroud)

样式表只是向 td 元素添加红色背景:

td {
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

最后是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>
Run Code Online (Sandbox Code Playgroud)

抱歉有大量代码,但它实际上非常基本。我想要的只是有一个按钮,单击该按钮即可下载 pdf 文件(此 pdf 是转换为 pdf 的 html 文件)。

它有点有效,但控制台输出如下:

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
Run Code Online (Sandbox Code Playgroud)

问题

pdfkit,它基本上调用wkhtmltopdf无法在文件夹内找到样式表文件static。我遇到这个问题的应用程序更加强大,使用了 boostrap 等,并且 pdf 输出格式错误是非常不可取的。

小智 7

单个 CSS 文件

css = 'example.css'
pdfkit.from_file('file.html', css=css)
Run Code Online (Sandbox Code Playgroud)

多个 CSS 文件

css = ['example.css', 'example2.css']
pdfkit.from_file('file.html', css=css)
Run Code Online (Sandbox Code Playgroud)

在你的情况下试试这个:

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