2

我有模板:

<!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没有特殊字符。我也试过字体。怎么做?

4

3 回答 3

1

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

于 2012-09-17T12:50:45.603 回答
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

于 2012-09-17T13:53:47.607 回答
0

解决方案之一是使用code2000字体

这适用于所有 unicode 字符。

于 2015-10-29T19:20:52.567 回答