【问题标题】:how to use python pdfkit with python flask webapp如何在 python flask webapp 中使用 python pdfkit
【发布时间】:2018-12-14 20:31:36
【问题描述】:

我尝试获取协议文件(例如:agreement.HTML),将其转换为 PDF 文件并将该文件下载到用户计算机。

我想使用 PDFkit 模块,在我的 webapp 上获取 html 文件并将生成的 pdf 下载到本地用户。

这怎么可能?

【问题讨论】:

标签: javascript python flask web-applications pdfkit


【解决方案1】:

如下例所示,设置项目目录如下: enter image description here

这是 app.py

的代码
from flask import Flask, render_template
import pdfkit
import os

app = Flask(__name__)
app.config['PDF_FOLDER'] = 'static/pdf/'
app.config['TEMPLATE_FOLDER'] = 'templates/'


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/convert')
def konversi():
    htmlfile = app.config['TEMPLATE_FOLDER'] + 'index.html'
    pdffile = app.config['PDF_FOLDER'] + 'demo.pdf'
    pdfkit.from_file(htmlfile, pdffile)
    return '''Click here to open the
    <a href="http://localhost:5000/static/pdf/demo4.pdf">pdf</a>.'''


if __name__ == '__main__':
    app.run(debug=True)

index.html

<html>
<head>
   <title>Demo pdfkit</title>
</head>
<body>
   <h2>Flask PDFKit</h2>

   <table border="1">
      <tr>
         <th width="90">ID</th>
         <th width="250">Title</th>
         <th width="150">writer</th>
         <th width="170">Publisher</th>
      </tr>
      <tr>
         <td>B001</td>
         <td>Learning Flask Framework</td>
         <td>Matt Copperwaite</td>
         <td>PACKT Publishing</td>
      </tr>
      <tr>
         <td>B002</td>
         <td>Flask By Example</td>
         <td>Gareth Dwyer</td>
         <td>PACKT Publishing</td>
      </tr>
      <tr>
         <td>B003</td>
         <td>Essential SQLAlchemy</td>
         <td>Rick Copeland</td>
         <td>OReilly</td>
      </tr>
   </table>

   <p><a href="http://localhost:5000/convert">Convert to PDF</a></p>
</body>
</html>

或者你可以使用这样的代码:

import pdfkit

# from file
pdfkit.from_file('templates/index.html', 'demo_from_file.pdf')

# from string
pdfkit.from_string('Hello World', 'demo_from_string.pdf')

# from url
pdfkit.from_url('https://www.google.com/', 'demo_from_url.pdf')

【讨论】:

  • 如果我想在 index.file 中传递数据并在生成 pdf 文件之前使用 djinja 显示,该怎么办。
  • @BostonKenne 这个link 可能会有所帮助
猜你喜欢
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
相关资源
最近更新 更多