Question

I'm using Django and my code to render the PDF is really typical:

t = loader.get_template('back/templates/content/receipt.html')
c = RequestContext(request, {
                             'pagesize': 'A4',
                             'invoice': invoice,
                             'plan': plan,
                             })

html = t.render(c)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result)
if not pdf.err:
    return HttpResponse(result.getvalue(), mimetype="application/pdf")

And the receipt.html is nothing unusual:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Squizzal Receipt</title>
    <style type="text/css">
        @page {
            size: {{pagesize}};
            margin: 1cm;
            word-spacing 1cm;
            @frame footer {
                -pdf-frame-content: footerContent;
                bottom: 0cm;
                margin-left: 9cm;
                margin-right: 9cm;
                height: 1cm;
            }
        }
    </style>
</head>
<body>
    <h1>Your Receipt</h1>
   <<SNIP>>

but none of the spaces in the pdf are rendered. All the words are right next to each other. I've tried normal spaces and "&nbsp" and the result is the same. For example the above would appear as "YourReceipt" in the pdf.

When I try using the command line version of pisa, it generates the pdf just fine with spaces between the words.

Any thoughts?

Était-ce utile?

La solution 2

Ok thanks to akonsu the problem seems to be how Django's HttpResponse is being treated (either on the server side or on the browser side).

Instead of

 return HttpResponse(result.getvalue(), mimetype="application/pdf")

Use:

 resp = HttpResponse(result.getvalue(), mimetype="application/pdf")
 resp['Content-Disposition'] = 'attachment; filename=receipt.pdf'
 return resp

This at least produces a result without spaces. Still no idea why the first way wasn't working.

Autres conseils

I had this same issue and didn't want to force the PDF to be downloaded from the browser. This turned out to be a platform specific issue: Google Chrome's native PDF viewer plugin fails to render spaces in certain documents on certain Linux distros when Microsoft TrueType fonts are not installed. See http://www.google.com/support/forum/p/Chrome/thread?tid=7169b114e8ea33c7&hl=en for details.

I fixed this by simply running the following commands in bash (adjust for your distro; this was on Ubuntu):

$ sudo apt-get install msttcorefonts

(Accept the EULA during the install process)

$ fc-cache -fv

After restarting Chrome (important!), the native PDF viewer correctly displayed the PDF with spaces.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top