gpt4 book ai didi

python - pisa html 到 pdf 问题,希腊重音字母与 django 一起使用

转载 作者:行者123 更新时间:2023-12-01 05:28:58 25 4
gpt4 key购买 nike

我正在 django 应用程序中使用 pisa 从 html 生成 pdf。我的查看代码如下

if request.method == 'POST':        
return write_to_pdf(request.POST['convert'], { }, 'file')

其中convert是一个TextArea,我从中获取要写入我的pdf文件的值

写入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)。为此,请向您的 html 模板添加一个 style 元素,如下所示:

<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>

现在,dejavusans字体可以从http://dejavu-fonts.org/wiki/Main_Page下载。此外,放置字体文件的位置也存在各种问题 - 我已经对 trouble in converting unicode template to pdf using xhtml2pdf 的回答提供了一些见解。 。第一步,我建议将这些字体放入 C:/fonts(如果使用 unix,则将其放入 /tmp/fonts),并使用 @ 的绝对 url字体,例如

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

之后,请检查我的答案,了解如何使用相对网址。

最后,我不得不提一下,我只使用 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))

关于python - pisa html 到 pdf 问题,希腊重音字母与 django 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20741435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com