利用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
上图:
版权声明:本文为wcl1598593原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。