有没有办法从django模板中使用pisa生成包含非ascii符号的pdf?

发布于 2024-08-09 02:58:05 字数 672 浏览 2 评论 0原文

我正在尝试使用以下代码段从模板生成 pdf:

def write_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)
    if not pdf.err:
        return http.HttpResponse(result.getvalue(), mimetype='application/pdf')
    except Exception('PDF error')

所有非拉丁符号均未正确显示,模板和视图使用 utf-8 编码保存。

我尝试将视图保存为 ANSI,然后保存为用户 unicode(html,"UTF-8"),但它会抛出 TypeError。

我还想也许是因为默认字体不支持 utf-8 所以根据 pisa 文档,我尝试在样式部分的模板主体中设置字体。

那仍然没有结果。

有人知道如何解决这个问题吗?

I'm trying to generate a pdf from template using this snippet:

def write_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)
    if not pdf.err:
        return http.HttpResponse(result.getvalue(), mimetype='application/pdf')
    except Exception('PDF error')

All non-latin symbols are not showing correctly, the template and view are saved using utf-8 encoding.

I've tried saving view as ANSI and then to user unicode(html,"UTF-8"), but it throws TypeError.

Also I thought that maybe it's because the default fonts somehow do not support utf-8
so according to pisa documentation I tried to set fontface in template body in style section.

That still gave no results.

Does any one have some ideas how to solve this issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

╄→承喏 2024-08-16 02:58:05

这对我有用:

pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8')

This does work for me:

pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8')
も让我眼熟你 2024-08-16 02:58:05

尝试替换

pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result)

pdf = pisa.pisaDocument(StringIO.StringIO(html), result, encoding='UTF-8')

或签出此答案 html to pdf for a Django网站?

Try replacing

pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result)

with

pdf = pisa.pisaDocument(StringIO.StringIO(html), result, encoding='UTF-8')

Or checkout this answer to html to pdf for a Django site?

冷情 2024-08-16 02:58:05

您需要修改您的 django 模板。在样式表中添加新字体,该字体将链接到包含文档中使用的字符的字体文件。并且该字体文件必须可以从您的服务器访问(在 Ubuntu 下,您可以在 /usr/share/fonts/truetype/ 目录中找到带有字体的文件)。例如:

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

然后,如果您有下一个 HTML 代码:

<div>Some non-latin characters</div>

您可以使用以下 CSS 规则以 DejaMono 字体显示该文本:

div { font-family: DejaMono; }

当我生成带有西里尔字符的 PDF 文档时,这对我有用。

You need to modify your django template. Add a new font face in the stylesheet that will link to a font file with characters used in your document. And that font file must be accessible from your server (under Ubuntu you can find files with fonts in /usr/share/fonts/truetype/ directory). For example:

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

Then if you have next HTML code:

<div>Some non-latin characters</div>

you can display that text in DejaMono font with this CSS rule:

div { font-family: DejaMono; }

This works for me when I generate PDF documents with cyrillic characters.

萌逼全场 2024-08-16 02:58:05

我在使用西里尔字母时也遇到了同样的问题。

该解决方案包含两个步骤:
1. 指出 HTML 文件中的字体文件

<style type="text/css">
@font-face {
  font-family: Arial; src: url("files/arial.ttf");
}
body {
  font-family: Arial;
}
</style>

2. 给出“pisa”根路径(以便它通过相对路径找到字体文件)
就我而言,它是这样的,

pdf = pisa.pisaDocument(html, result, path=PATH_TO_DJANGO_PROJECT)

因为字体放置在 PATH_TO_DJANGO_PROJECT/files/arial.ttf

I faced the same problem with cyrillic characters.

The solution contained two steps:
1. Point out the font file in your HTML file

<style type="text/css">
@font-face {
  font-family: Arial; src: url("files/arial.ttf");
}
body {
  font-family: Arial;
}
</style>

2. Give "pisa" root path (so that it find font file by relative path)
in my case it was something like this

pdf = pisa.pisaDocument(html, result, path=PATH_TO_DJANGO_PROJECT)

because fonts were placed at PATH_TO_DJANGO_PROJECT/files/arial.ttf

我三岁 2024-08-16 02:58:05

我正在使用 xhtml2pdf 版本 0.2.4
我遇到了同样的问题,我能够使用这种编码来解决:

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html = template.render(context_dict)
    result = BytesIO()

    # PDF
    pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

然后在我看来,我定义如下:

def download_pdf(request, pk):
item = get_object_or_404(object, id=pk)
if item:
    context ={
        'item': item
    }
    template_name = 'template.html'
    pdf = render_to_pdf(template_name, context)
    return HttpResponse(pdf, content_type='application/pdf')

else:
    messages.info(request, 'Item not found')
    return redirect('home')

我的 HTML:

{% load static %}
{% load humanize %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="icon" type="image/gif" href="{% static 'images/profile.png' %}" />
    <title>{{ item.scientific_name}}</title>
    <link rel="stylesheet" href="{% static 'style/Bootstrap/css/bootstrap.min.css' %}">

   <style>
    @page {
        size: letter;
        margin: 2cm;

        @frame footer_frame {
            /* Another static Frame */
            -pdf-frame-content: footer_content;
            left: 50pt;
            width: 512pt;
            top: 760pt;
            height: 50px;
        }

        table {
            -pdf-keep-with-next: true;
        }
    }

    ul {
        list-style-type: none;
    }

    ul li span {
        font-weight: bold;
    }
</style>

I am using xhtml2pdf version 0.2.4
I faced the same issue and I was able to resolve using this encoding:

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html = template.render(context_dict)
    result = BytesIO()

    # PDF
    pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

Then in my views, I have defined like:

def download_pdf(request, pk):
item = get_object_or_404(object, id=pk)
if item:
    context ={
        'item': item
    }
    template_name = 'template.html'
    pdf = render_to_pdf(template_name, context)
    return HttpResponse(pdf, content_type='application/pdf')

else:
    messages.info(request, 'Item not found')
    return redirect('home')

My HTML:

{% load static %}
{% load humanize %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="icon" type="image/gif" href="{% static 'images/profile.png' %}" />
    <title>{{ item.scientific_name}}</title>
    <link rel="stylesheet" href="{% static 'style/Bootstrap/css/bootstrap.min.css' %}">

   <style>
    @page {
        size: letter;
        margin: 2cm;

        @frame footer_frame {
            /* Another static Frame */
            -pdf-frame-content: footer_content;
            left: 50pt;
            width: 512pt;
            top: 760pt;
            height: 50px;
        }

        table {
            -pdf-keep-with-next: true;
        }
    }

    ul {
        list-style-type: none;
    }

    ul li span {
        font-weight: bold;
    }
</style>
执手闯天涯 2024-08-16 02:58:05

如果您调用 createPDF 而不是 pisaDocument 方法,则可以使用

pisa.CreatePDF(html.encode('UTF-8'), response, link_callback=fetch_resources, encoding='UTF-8')

If you are calling createPDF instead of the pisaDocument method, you can use

pisa.CreatePDF(html.encode('UTF-8'), response, link_callback=fetch_resources, encoding='UTF-8')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文