首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在python flask webapp中使用python pdfkit

如何在python flask webapp中使用python pdfkit
EN

Stack Overflow用户
提问于 2018-07-06 17:11:20
回答 1查看 3.5K关注 0票数 2

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

我想使用PDFkit模块,在我的网页应用程序上获得html文件,并下载生成的pdf文件给本地用户。

那件事怎么可能?

EN

回答 1

Stack Overflow用户

发布于 2018-08-05 07:34:35

就像下面这个例子,像这样设置项目目录:enter image description here

这是app.py的代码

代码语言:javascript
复制
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

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
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')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51206880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档