【问题标题】:Reportlab doesn't process & and <Reportlab 不处理 & 和 <
【发布时间】:2015-07-21 22:26:25
【问题描述】:

我正在使用 Django 和 Reportlab 生成 pdf 文件。有时用户会使用 Reportlab 确定为无效的字符,我得到这个:

ValueError:段落中的 xml 解析器错误(伪造的

除了限制用户输入之外,还有什么办法可以避免这种情况?

这是代码的精简版:

def generate_report(request, obj_id):

    obj = Model.objects.get(pk=obj_id)
    width, height = letter
    styles = getSampleStyleSheet()

    doc = SimpleDocTemplate(settings.MEDIA_ROOT + "/pdf/" + str(obj.id) + ".pdf", pagesize=letter,rightMargin=72,leftMargin=72,topMargin=160,bottomMargin=100)
    Story = []        

    Story.append('Title', h1))

    text = obj.test_to_display
    for line in text.splitlines():
        Story.append(Spacer(1,0.1*inch))
        p = Paragraph(line, style)
        Story.append(p)        

    doc.build(Story)

    return HttpResponseRedirect("/media/pdf/" + str(obj.id) + ".pdf")

【问题讨论】:

    标签: django reportlab


    【解决方案1】:

    我以前从未直接使用过 ReportLab,但根据错误消息,将这些字符转换为 html 实体应该很简单。

    以下是有关如何使用 python cgi 库快速轻松地完成此操作的快速指南: http://wiki.python.org/moin/EscapingHtml

    或者 xml 特定版本可能会稍微好一些,因为它似乎是 reportlab 一直在生成 xml,这就是它的破坏之处(尽管大多数字符实体都是共享的) http://wiki.python.org/moin/EscapingXml

    【讨论】:

      【解决方案2】:

      我之前在创建标题时遇到过 & 字符的问题。

      我通过以下方式解决了这个问题:

      from cgi import escape
      Paragraph(escape(self.name), self.styles['cover_subtitle'])
      

      也许你可以试试:

      from cgi import escape
      p = Paragraph(escape(line), style)
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2011-03-05
        • 2022-08-04
        • 1970-01-01
        • 2014-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多