Django CBV:以编程方式将HTML页面保存为服务器上的PDF文件 [英] Django CBV: Programmatically save HTML page to PDF file on the server

查看:43
本文介绍了Django CBV:以编程方式将HTML页面保存为服务器上的PDF文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

访问相关的URL,将显示一个html页面。我需要以编程方式将此html页面保存到服务器上的pdf文件中。

Visiting the relevant url, an html page is rendered. I need to programmatically save this html page to a pdf file on the server.

views.py

class PdfView(DetailView):
    model = TheModel
    template_name = 'pdf.html'

urls.py

urlpatterns = [
    url(
        r'^(?P<pk>[0-9]+)/$',
        PdfDataView.as_view(),
        name='pdf-data',
    ),
]


推荐答案

以下解决方案保存了HTTP请求期间的网页,然后将HTTP响应提供给浏览器。

The following solution saves a pdf version of the web page during the HTTP request, before the HTTP response is served to the browser.

我使用了 weasyprint ,因为它可以立即处理Unicode字符。

I used weasyprint because it managed to take care of the unicode characters out of the box.

views.py

from weasyprint import HTML

class PdfView(DetailView):
    model = TheModel
    template_name = 'pdf.html'

    def get(self, request, *args, **kwargs):
        template_response = super().get(self, request, *args, **kwargs)
        HTML(string=template_response.rendered_content).write_pdf(
            '/path/to/test.pdf',
            stylesheets=['/path/to/pdf.css']
        )
        return template_response

在视图之外,更好的解决方案是使用请求以获取HTML页面,然后创建pdf文件。最好这样做,因为服务器不必等待pdf的创建,从而有可能阻止其他请求等待被服务器化:

A better solution, outside the view, would be to use requests to fetch the HTML page and then create the pdf file. It is better because the server will not have to wait for the pdf to be created, potentially blocking other requests waiting to be serverd:

>>>import requests
>>>resp = requests.get('http://my-url/object_id')
>>>HTML(string=resp.content).write_pdf('/path/to/test.pdf', stylesheets=['/path/to/pdf.css'])

这篇关于Django CBV:以编程方式将HTML页面保存为服务器上的PDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆