2015-11-02 140 views
2

我目前正在使用Flask構建一個web應用程序。我的主管要求一個功能應該是將當前頁面保存爲PDF(用於打印)。爲此,我使用pdfkit。在任何人提出使用weasyprint之前,我試圖安裝它2小時無濟於事,所以我放棄了這一點。我正在使用Bootstrap css和它的JavaScript來讓應用程序看起來更愉快一點。pdfkit不加載css和JavaScript

我使用下面的文件結構(如提出了一個教程,Flask

+-- name_of_app 
| +-- static 
|  +-- css 
|   +-- css files 
|  +-- js 
|   +-- javascript files 
| +-- templates 
|  +-- .html templates 
| +-- __init__.py 
| +-- config.py 
| +-- forms.py 
| +-- views.py 
+-- run.py 

只試着pdfkit出來,我生成PDF每次我在所有的功能生成的頁面時,即時間這些路由在views.py。所有頁面都基於以下模板

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta charset="UTF-8"> 
     <link href="static\css\bootstrap.css" rel="stylesheet" media="screen"> 
     <link href="static\css\bootstrap-theme.css" rel="stylesheet"> 
     <script src="http://code.jquery.com/jquery-latest.js"></script> 
     <script src="static\js\bootstrap.js"></script> 
     <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
     {% if title %} 
     <title>{{ title }} - Timeseries Project</title> 
     {% else %} 
     <title>Welcome to the Timeseries Project</title> 
     {% endif %} 
    </head> 
    <body> 
     <div class="navbar navbar-default"> 
      <div class="navbar-inner"> 
       <a class="navbar-brand active" href="/">Home</a> 
       <a class="navbar-brand" href="/">Save as PDF</a> 
      </div> 
     </div> 
     {% block content %}{% endblock %} 
    </body> 
</html> 

使用提供的css和JS文件加載的網頁非常漂亮。然而,pdfkit輸出以下警告因此

Warning: Failed to load file:///C:/Users/my_user/AppData/Local/Temp/static/css/bootstrap.css (ignore) 
Warning: Failed to load file:///C:/Users/my_user/AppData/Local/Temp/static/css/bootstrap-theme.css (ignore) 
Warning: Failed to load file:///C:/Users/my_user/AppData/Local/Temp/static/js/bootstrap.js (ignore) 

我試圖解決的問題是:我如何獲得pdfkit其中的一個方法被執行的文件夾中尋找static(即views.py),和不在AppData

+0

是一個只打印樣式表不是一種選擇,由於應用程序的性質是什麼? – Blazemonger

+0

嗯,不是很確定什麼「只打印樣式表」意味着我害怕,你能否詳細說明一下? (我沒有網絡開發經驗) – Tingiskhan

+1

http://www.smashingmagazine.com/2011/11/how-to-set-up-a-print-style-sheet/ – Blazemonger

回答

2

要生成靜態文件的URL,使用特殊'static'端點名稱:http://flask.pocoo.org/docs/0.10/quickstart/#static-files

<link href="{{ url_for('static', filename='css/bootstrap.css) }}" rel="stylesheet" media="screen"> 
<link href="{{ url_for('static', filename='css/bootstrap-theme.css) }}" rel="stylesheet"> 
+1

哇,如果這很簡單,我會躺下哭泣。非常感謝你的回答,明天我會在辦公室試試吧, – Tingiskhan

+0

嗯,我嘗試過實現這一點,但是現在我得到了相同的警告,但對於路徑'無法加載文件:/ // static/css/bootstrap-theme.css' – Tingiskhan

+1

嘗試使用絕對URL:'url_for('static',filename ='css/bootstrap.css',_external = True)' –