[英]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.