views:

617

answers:

5

Hi. i'm trying to generate a pdf from template using this snippet:

def write_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()
    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result)
    if not pdf.err:
        return http.HttpResponse(result.getvalue(), mimetype='application/pdf')
    except Exception('PDF error')

but all non-latin symbols are not showing correctly, the template and view are saved using utf-8 encoding.

i've tried saving view as ANSI and then to user unicode(html,"UTF-8"), but it throws TypeError.

Also i thought that maybe it's because the default fonts somehow do not support utf-8 so according to pisa documentation i tried to set fontface in template body in style section.

that still gave no results.

Does any one have some ideas how to solve this issue?

+1  A: 

Try replacing

pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result)

with

pdf = pisa.pisaDocument(StringIO.StringIO(html), result, encoding='UTF-8')

Or checkout this answer to html to pdf for a Django site?

jitter
after replaceing got pdf full of unreadable data,checked the solution, the method doesn't differ much from what i use, but i still tested it, with html.encode("ISO-8859-1") it throws: "'latin-1' codec can't encode character u'\ufeff' in position 0: ordinal not in range(256)"with encode("UTF-8") it returns pdf but the same as i hve got previously - non-ascii symbols are still not rendered properly.
mihailt
+2  A: 

This does work for me:

pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8')
yedpodtrzitko
A: 

You need to modify your django template. Add a new font face in the stylesheet that will link to a font file with characters used in your document. And that font file must be accessible from your server (under Ubuntu you can find files with fonts in /usr/share/fonts/truetype/ directory). For example:

@font-face {
  font-family: DejaMono; 
  src: url(font/DejaVuSansMono.ttf);
}

Then if you have next HTML code:

<div>Some non-latin characters</div>

you can display that text in DejaMono font with this CSS rule:

div { font-family: DejaMono; }

This works for me when I generate PDF documents with cyrillic characters.

Bohdan
A: 

Hi, have you solved this problem? I ran into the same issue when trying to generate some paragraphs in Hungarian language. The characters like ő ű Ő Ű are not shown. I have tried it the way as Bohdan said but it doesn't work. Do you have some idea about how can I solve the problem?

Vekony Laszlo
A: 

If you are calling createPDF instead of the pisaDocument method, you can use pisa.CreatePDF(html.encode("UTF-8"),response,link_callback=fetch_resources,encoding='UTF-8')

Sriram