Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

python - Python3 Django -> HTML to PDF

There are a lot of different ways of generating pdfs from a django webpage in python2. The most clean, probably, is pisa and reportlab. These do not work for python3 though.

So far, the only method I've had success with is to render the template, write it to a file, and then use wkhtmltopdf via subprocess.popen. This works alright, but it doesn't load any of my static files, such as css and images.

Are there any proper solutions? can wkhtmltopdf read my staticfiles from the command line, in some way, or is there a library like pisa/reportlab, which supports python3?

I haven't been able to finde such a library

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use Weasyprint. You could easily render directly.

You could do something like that:

    html = HTML(string=htmlstring)
    main_doc = html.render()
    pdf = main_doc.write_pdf()
    return HttpResponse(pdf, content_type='application/pdf')

To render your Django view to HTML, you could simply use the shortcut render_to_string(self.template_name, context, context_instance=RequestContext(self.request))

Be aware, when using This with a Synchronous Webserver/WSGI Server ALL requests will be blocked until the PDF is rendered. So consider using an ASYNC Worker.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...