[英]pisa html to pdf issue with greek stressed letters used with django
我正在使用比萨在Django应用程序中从html生成pdf。 我的查看代码如下
if request.method == 'POST':
return write_to_pdf(request.POST['convert'], { }, 'file')
其中convert是一个TextArea,我从中获取要写入pdf文件的值
write_to_pdf
def fetch_resources(uri, rel):
path = '%s/media/pdf/' % RHOMBUS_PATH
return path
def write_to_pdf(template_data, context_dict, filename):
print template_data
template = Template(template_data)
context = Context(context_dict)
html = template.render(context)
print html
result = StringIO.StringIO()
pdf = pisa.CreatePDF(html.encode('UTF-8'), result, link_callback=fetch_resources, encoding='UTF-8')
print result.getvalue()
if not pdf.err:
response = http.HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s.pdf' % filename
response.write(result.getvalue())
return response
return http.HttpResponse('Problem creating PDF: %s' % cgi.escape(html))
当TextArea具有像希腊语这样的压力字符时,生成的pdf会出现问题
ά έ
等等。我尝试更改编码,但一无所获。 任何帮助,将不胜感激。
我也遇到了希腊字符问题(而不是我收到黑框的强调字符)。 第一步,您需要将字体更改为适当的字体(例如dejavu sans)。 为此,将style
元素添加到html模板中,如下所示:
<style type='text/css'>
@font-face {
font-family: "DejaVuSansMono";
src: url("fonts/DejaVuSansMono.ttf");
}
@font-face {
font-family: "DejaVuSansMono";
src: url("fonts/DejaVuSansMono-Bold.ttf");
font-weight: bold;
}
@font-face {
font-family: "DejaVuSansMono";
src: url("fonts/DejaVuSansMono-Oblique.ttf");
font-style: italic, oblique;
}
@font-face {
font-family: "DejaVuSansMono";
src: url("fonts/DejaVuSansMono-BoldOblique.ttf");
font-weight: bold;
font-style: italic, oblique;
}
*, html {
font-family: "DejaVuSansMono";
}
html {
padding:10pt;
}
</style>
现在,可以从http://dejavu-fonts.org/wiki/Main_Page下载dejavusans字体。 另外,放置字体文件的位置也有很多问题-我对使用xhtml2pdf将unicode模板转换为pdf时遇到的问题提供了一些见解。 第一步,我建议将这些字体放入C:/fonts
(如果使用unix,则为/tmp/fonts
),并为@font-face
使用绝对URL,例如
@font-face {
font-family: "DejaVuSansMono";
src: url("c:/fonts/DejaVuSansMono.ttf");
}
之后,检查我的答案以查看如何使用相对URL。
最后,我不得不提一下,我仅使用dejavu-sans测试了上述方法(并且工作正常)-但是,我真的想知道上述解决方案是否可以与其他字体(例如Calibry)一起使用,如果您对其进行了测试请提供反馈。
如果上述方法不起作用,请查看我使用的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, path= settings.PROJECT_PATH)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return HttpResponse('<pre>%s</pre>' % escape(html))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.