Tin*_*han 6 javascript css python pdfkit flask
我目前正在使用Flask. 我的主管要求一个功能应该是将当前页面保存为 PDF(用于打印)。为此,我正在使用pdfkit. 在有人提议使用之前weasyprint:我尝试安装它 2 小时无济于事,所以我放弃了。我正在使用Bootstrapcss 及其 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
Run Code Online (Sandbox Code Playgroud)
为了尝试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>
Run Code Online (Sandbox Code Playgroud)
使用提供的 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)
Run Code Online (Sandbox Code Playgroud)
因此,我试图解决的问题是:如何在执行其方法之一的文件夹中pdfkit查找static(即views.py),而不是在 中查找AppData?
要为静态文件生成 URL,请使用特殊的'static'端点名称:http : //flask.pocoo.org/docs/0.10/quickstart/#static-files
<link href="{{ url_for('static', filename='css/bootstrap.css') }}" rel="stylesheet" >
<link href="{{ url_for('static', filename='css/bootstrap-theme.css') }}" rel="stylesheet">
Run Code Online (Sandbox Code Playgroud)
更新:
使用_external=True也可以通过提供绝对网址来解决问题。例如:
<link href="{{ url_for('static', filename='css/bootstrap.css', _external=True) }}" rel="stylesheet" >
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7364 次 |
| 最近记录: |