django中Html转PDF

利用pdfcrowd 实现HTML转 PDF的功能

(1)环境:ubuntu12.04/python 2.7.8/Django 1.7

(2)安装

$ pip install pdfcrowd

或者fork下安装包,然后安装

python setup.py install
(3)注册

点击打开链接

(4)使用

import pdfcrowd
from django.http import HttpResponse

def generate_pdf_view(request):
   username = 'username'
   apikey = 'apikey' 
   try:
        # create an API client instance
        client = pdfcrowd.Client(username, apikey)

        # convert a web page and store the generated PDF to a variable
        pdf = client.convertURI("http://www.baidu.com")
        # 或者根据Html或本地文件转换
        # pdf = client.convertHtml('<head></head><body>My Page</body>')
        # pdf = clent.convertFile('/var/www/xxx.html') # 必须是绝对路径
        # set HTTP response headers
        # response = HttpResponse(mimetype="application/pdf")
        # 注意:新版本的django HttpResponse不支持mimetype,改成了content_type
       response = HttpResponse(content_type="application/pdf")
       response["Cache-Control"] = "max-age=0" 
       response["Accept-Ranges"] = "none" 
       response["Content-Disposition"] = "attachment; filename=xxx.pdf" 
       # send the generated PDF 
       response.write(pdf) 
   except pdfcrowd.Error, why: 
       response = HttpResponse(mimetype="text/plain") 
       response.write(why) 
   return response

上图:

django中Html转PDF_第1张图片

你可能感兴趣的:(python,django,ubuntu,HTML2PDF)