Skip to main content
 首页 » 编程设计

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

2025年05月04日9wayfarer

我正在尝试在 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 是转换为 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 

问题

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

请您参考如下方法:

单个 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