How to generate a PDF from an HTML / CSS (including images) source in Python? [closed]

不想你离开。 提交于 2021-02-06 12:51:13

问题


Let's say I've got an HTML / CSS page with some images in it, and I wanted to generate a PDF from that source in Python - possible?


回答1:


http://www.xhtml2pdf.com/

install was a little quirky for me, but otherwise it worked fine.




回答2:


You can do something like this using Pisa:

def receipt(request, id):
    import ho.pisa as pisa
    from django.template.loader import render_to_string
    from datetime import datetime

    r = get_or_404(id, request.affiliate)    
    now = datetime.now()
    contents = render_to_string('home/reservations/receipt.html', {
        'reservation': r,
        'today': now
    })
    filename = now.strftime('%Y-%m-%d') + '.pdf'
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=' + filename
    pdf = pisa.CreatePDF(contents, response)
    if pdf.err:
        message(request, 'Unable to generate the receipt.')
        return HttpResponseRedirect(reverse('view_reservation', args=[r.id]))    
    else:
        return response

(This is a Django view that generates a receipt but obviously you can use Pisa in whatever setting)

You're going to have to tweak the HTML to make it play as nice as possible with Pisa, though.




回答3:


There is wkhtmltopdf a possibly better option which I recently started using for my project. It not only supports almost complete CSS but also javascript. Try wkhtmltopdf command first to understand it's power. Then you use it's python extension.

Here are links

  • https://github.com/mreiferson/py-wkhtmltox
  • http://code.google.com/p/wkhtmltopdf/

It was slightly tricky to install for me. So I wrote this quick and dirty script.

  • https://github.com/shon/cowspa3/blob/master/wkhtmltox-installer.sh


来源:https://stackoverflow.com/questions/786463/how-to-generate-a-pdf-from-an-html-css-including-images-source-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!