[reportlab-users] Problem generating PDF from Django/Python HTML Template

Tim Roberts timr at probo.com
Tue Oct 10 12:40:31 EDT 2006


Lucas Cardona wrote:

>Hello, 
>
>I have the following view in my Django app:
>def print_pdf(request, language):
>    ch = ContentHelper(language)
>    # Create the HttpResponse object with the appropriate PDF headers.
>    response = HttpResponse(mimetype='application/pdf')
>    response['Content-Disposition'] = 'attachment; calgovcouncil_calendar.pdf'
>  
>

That's supposed to say
    response['Content-Disposition'] = 'attachment;
filename=calgovcouncil_calendar.pdf'

>    buffer = StringIO()
>
>    # Create the PDF object, using the StringIO object as its "file."
>    p = canvas.Canvas(buffer)
>
>    # Draw things on the PDF. Here's where the PDF generation happens.
>    # See the ReportLab documentation for the full list of functionality.
>    #p.drawString(100, 100, "Hello world.")
>    c = MyRequestContext(request, 
>	       { 'content' : ch,
>	          'language' : language,
>	        }
>	    )
>	
>    #challenge/dayview.html
>    t = loader.get_template('information/24hrfitfacts.html')
>    p.drawString(0,820, HttpResponse(t.render(c)))
>
>    # Close the PDF object cleanly.
>    p.showPage()
>    p.save()
>
>    # Get the value of the StringIO buffer and write it to the response.
>    pdf = buffer.getvalue()
>    buffer.close()
>    response.write(pdf)
>    return response
>  
>

I tend to use something like this instead of those last 5 lines:

    # Read the PDF file into the response.

    buffer.seek(0)
    response.write( buffer.read() )
    return response

>Now, this generates the PDF but the generated PDF doesn't contain the contents of the template but it only has one line:
>
>n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">n<
>
>Any idea why this is happenning? I need the HTML to be generated dynamically as it contains information related to the user that is browsing the application.
>  
>

That's probably coming from a Cheetah SkeletonPage.tmpl.  Are you
calling this from inside a Cheetah template?  Why?  Why not just call
this directly and skip the template?  You can't use any HTML anyway when
you are return this.  The output must consist of NOTHING other than your
PDF content.

You can eliminate the DOCTYPE header by using
    #attr docType=''
but there are other things in the SkeletonPage.tmpl that will screw up
your PDF, including a bunch of blank lines.

-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the reportlab-users mailing list