簡體   English   中英

如何在Flask應用程序中將樣式表文件鏈接到pdfkit?

[英]How to link stylesheet files to pdfkit in Flask application?

我想創建使用HTML頁面PDF pdfkitFlask的應用程序,但我有麻煩使用時加載靜態文件(樣式表) 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輸出格式錯誤是非常不可取的。

假設您的應用程序具有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)

單個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

您的代碼會導致一個鏈接,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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM