如何使用unicode字符在Django中生成pdf?

时间:2012-09-17 12:42:07

标签: django django-templates

我有模板:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>PRINT FILE</title>
    </head>
    <body>
        <center>ąśżźćę</center>
    </body>
</html>

并查看:

@login_required
def print_to_pdf(request):
    data = dict()
    return render_to_pdf('print.html', { 'pagesize':'A4', 'pdf': '1', 'data': data })

和render_to_pdf:

def render_to_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, link_callback=fetch_resources, encoding='utf-8')
    if not pdf.err:
        return HttpResponse(result.getvalue(), mimetype='application/pdf')
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

def fetch_resources(uri, rel):
    path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
    return path

但是pdf没有特殊字符。我也尝试过使用font-face。怎么做?

3 个答案:

答案 0 :(得分:1)

您可以使用 wkhtmltopdf 从Html生成pdf文件,它支持Unicode字符

答案 1 :(得分:0)

我写(修改:http://boris.kodmasin.net/python:djangoandwkhtmltopdf)这个函数:

def get_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)

    import subprocess
    wkhtml2pdf = subprocess.Popen((settings.WKHTML2PDF_COMMAND,
                                   "--footer-right",
                                   "[page]/[toPage]",
                                   "--print-media-type",
                                   "--encoding",
                                   "UTF-8",
                                   "-",
                                   "-"),
                                  stdin=subprocess.PIPE,
                                  stdout=subprocess.PIPE)
    wkdata = wkhtml2pdf.communicate(html.encode('utf8'))
    pdf = wkdata[0];

    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=printfile.pdf'
    response.write(pdf)
    return response

并查看:

@login_required
def print_to_pdf(request):
    data = dict()
    return get_pdf('print.html', { 'data': data })

在settings.py中您必须设置WKHTML2PDF_COMMAND变量(带路径的程序名称)。

wkhtml在这里:http://code.google.com/p/wkhtmltopdf/downloads/list

答案 2 :(得分:0)

其中一个解决方案是使用code2000字体

这适用于所有unicode字符。