用django创建PDF(wkhtmltopdf) [英] Creating PDFs with django (wkhtmltopdf)

查看:829
本文介绍了用django创建PDF(wkhtmltopdf)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以提供一个全面的例子,说明如何在 django 中获取视图以返回一个 PDF 使用 wkhtmltopdf django-wkhtmltopdf 附带的示例数量有限,他们假设我没有的知识水平。我已经浏览了源代码,但是我无法使用它的头或尾(例如, PDFTemplateView PDFTemplateResponse之间的区别?!?)



我将非常感谢任何帮助。



b
$ b

  def some_view(request,sID):
something = get_object_or_404(Something,id = sID)
return render_to_response .html',{'something':something},context_instance = RequestContext(request))

我得到以下简单的视图,为我提供一个 pdf ,而不是一个 html 文件?



编辑2



我目前正在玩:

  def pdf_view(request,sID):
template ='pdf.html'
something = get_object_or_40 4(Something,id = sID)
context = {
'something':Something,
'object_for_header_and_footer':something.object_for_header_and_footer,
}
cmd_options = settings。 WKHTMLTOPDF_CMD_OPTIONS

返回PDFTemplateResponse(request = request,
context = context,
template = template,
filename ='something',
header_template ='header .html',
footer_template ='footer.html',
cmd_options = cmd_options)

但是我得到'str'对象在 /usr/local/lib/python2.7/dist-中没有属性'update' wkhtmltopdf中的packages / wkhtmltopdf / utils.py第74行。我不知道是否开始黑客wkhtmltopdf?!??

解决方案

PDFTemplateView和PDFTemplateResponse之间的区别是视图是一个基于类的视图。并且PDFTemplateResponse呈现pdf数据并设置正确的响应头。要添加页眉和页脚:

 #urls.py 

from django.conf.urls.defaults导入*
从wkhtmltopdf.views导入PDFTemplateView


urlpatterns = patterns('',
...
url(r'^ pdf / $ ',PDFTemplateView.as_view(template_name ='my_template.html',
filename ='my_pdf.pdf',
header_template ='my_header_template.html',
footer_template ='my_footer_template.html'
...
),name ='pdf'),

在浏览器中打开pdf /将基于my_template.html my_header_template.html和my_footer_template.html开始下载my_pdf.pdf。



高级示例显示如何子类化PDFTemplateView扩展和更改PDFTemplateView的逻辑。要了解发生什么,请参阅使用基于类的视图



喜欢 header_template footer_template 定义一个 response_class 。因为PDFTemplateResponse是默认值,所以您不需要定义它。



编辑



以下简单视图为您提供了pdf而不是HTML。这不是使用django-wkhtmltopdf。您可以在html2pdf函数中使用wkhtmltopdf。

  def some_view(request):
t = loader.get_template('myapp /template.html')
c = RequestContext(request,{'foo':'bar'})
html = t.render(c)
pdf_data = html2pdf(html)#你最喜欢html2pdf generator
response = HttpResponse(pdf_data,content_type ='application / pdf')
response ['Content-Disposition'] ='attachment; filename =some_filename.pdf'
return response

编辑2



一个简单的上下文视图:



template.html

 <!DOCTYPE html> 
< html>
< head>
< meta charset =utf-8/>
< title> Untitled< / title>
< / head>
< body>
< h1> {{title}}< / h1>
< / body>
< / html>

urls.py

  from views import MyPDFView 

urlpatterns = patterns('',
(r'^ pdf /',MyPDFView.as_view()),

views.py

 code> from django.views.generic.base import从wkhtmltopdf.views导入查看
导入PDFTemplateResponse

class MyPDFView(View):
template ='template.html'
context = {'title':'Hello World!'}

def get(self,request):
response = PDFTemplateResponse(request = request,
template = self.template,
filename =hello.pdf,
context = self.context,
show_content_in_browser = False,
cmd_options = {'margin-top':50, },

返回答复

编辑3



如果您使用DetailView,可以将对象添加到上下文中:

  url(r'^ books / (?P< pk> \d +)/ $',MyPDFView.as_view(),name ='book-detail'),


class MyPDFView(DetailView):
template ='pdftestapp / template.html'
context = {'title':'Hello World!'}
model = Book

def get(self,request,* args,** kwargs):
self.context ['book'] = self.get_object()

response = PDFTemplateResponse(request = request,
template = self.template ,
filename =hello.pdf,
context = self.context,
show_content_in_browser = False,
cmd_options = {'margin-top':50,}

返回响应


Could someone please provide me with a comprehensive example of how to get a view in django to return a PDF using wkhtmltopdf. There are limited number of examples that come with django-wkhtmltopdf and they presume a level of knowledge I just don't have. I have looked through the source code but I can't make heads or tails of how to use it (for example whats the difference between PDFTemplateView and PDFTemplateResponse?!?)

I would be very grateful for any help.

BTW(I'm using templates for the header and footer as well)

EDIT

def some_view(request,sID):
    something = get_object_or_404(Something,id=sID)
    return render_to_response('something.html', {'something':something}, context_instance=RequestContext(request))

How would I get the following simple view to provide me with a pdf instead of an html file?

EDIT 2

I am currently playing around with:

def pdf_view(request,sID):
    template = 'pdf.html'
    something = get_object_or_404(Something,id=sID)
    context = {
        'something' : Something,
        'object_for_header_and_footer': something.object_for_header_and_footer,
    }
    cmd_options = settings.WKHTMLTOPDF_CMD_OPTIONS

    return PDFTemplateResponse(request=request,
        context=context,
        template=template,
        filename='something',
        header_template='header.html',
        footer_template='footer.html',
        cmd_options=cmd_options)

but I am getting 'str' object has no attribute 'update' in /usr/local/lib/python2.7/dist-packages/wkhtmltopdf/utils.py in wkhtmltopdf, line 74. I don't know whether to starting hacking wkhtmltopdf?!?!

解决方案

The difference between PDFTemplateView and PDFTemplateResponse is that the view is a class-based view. And PDFTemplateResponse renders the pdf data and sets the right response headers. To add header and footer:

# urls.py

from django.conf.urls.defaults import *
from wkhtmltopdf.views import PDFTemplateView


    urlpatterns = patterns('',
        ...
        url(r'^pdf/$', PDFTemplateView.as_view(template_name='my_template.html',
                filename='my_pdf.pdf', 
                header_template='my_header_template.html', 
                footer_template='my_footer_template.html', 
                ...
                ), name='pdf'),
    )

Opening pdf/ in your browser will start a download of my_pdf.pdf based on the my_template.html, my_header_template.html and my_footer_template.html.

The advanced example shows how to subclass PDFTemplateView extending and changing the logic of PDFTemplateView. To understand what happens read Using class based views.

Like header_template and footer_template you can define a response_class. Because PDFTemplateResponse is the default, you don't have to define it.

EDIT

The following simple view provides you with a pdf instead of an html. This is not using django-wkhtmltopdf. You could use wkhtmltopdf in your html2pdf function.

def some_view(request):
    t = loader.get_template('myapp/template.html')
    c = RequestContext(request, {'foo': 'bar'})
    html = t.render(c)
    pdf_data = html2pdf(html) # Your favorite html2pdf generator
    response = HttpResponse(pdf_data, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="some_filename.pdf"'
    return response

EDIT 2

A simple view with context:

template.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Untitled</title>
</head>
<body>
    <h1>{{ title }}</h1>
</body>
</html>

urls.py

from views import MyPDFView

urlpatterns = patterns('',
    (r'^pdf/', MyPDFView.as_view()),
)

views.py

from django.views.generic.base import View
from wkhtmltopdf.views import PDFTemplateResponse

class MyPDFView(View):
    template='template.html'
    context= {'title': 'Hello World!'}

    def get(self, request):
        response = PDFTemplateResponse(request=request,
                                       template=self.template,
                                       filename="hello.pdf",
                                       context= self.context,
                                       show_content_in_browser=False,
                                       cmd_options={'margin-top': 50,},
                                       )
        return response

EDIT 3

If you use a DetailView, you can add the object to context:

url(r'^books/(?P<pk>\d+)/$', MyPDFView.as_view(), name='book-detail'),


class MyPDFView(DetailView):
    template='pdftestapp/template.html'    
    context= {'title': 'Hello World!'}
    model = Book

    def get(self, request, *args, **kwargs):        
        self.context['book'] = self.get_object()

        response=PDFTemplateResponse(request=request,
                                     template=self.template,
                                     filename ="hello.pdf",
                                     context=self.context,
                                     show_content_in_browser=False,
                                     cmd_options={'margin-top': 50,}
                                     )
        return response

这篇关于用django创建PDF(wkhtmltopdf)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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