【问题标题】:converting html to pdf using pisa使用比萨将html转换为pdf
【发布时间】:2020-02-04 12:33:25
【问题描述】:

我正在尝试使用现有的 DJANGO HTML 模板生成 PDF。我将上下文数据动态传递到模板中,然后尝试将其转换为 PDF。

然而,我一直遇到这个

文件“C:\Users\EliteBook\Desktop\Virtual_Environment\app\lib\site-packages\reportlab\platypus\tables.py”,第 265 行, init raise ValueError("%s data error - %d rows在数据中,但在行高中为 %d" % (self.identity(),nrows, len(rowHeights))) ValueError: with cell(0,0) contains 'size=x' data error - 16 行数据但 15 行行高

当这行代码执行时...

pdf = pisa.pisaDocument(BytesIO(html.encode("cp1252", 'ignore')), 结果)

我查看了 PISA 和 REPORTLAB 论坛,但似乎没有找到合适的解决方案。

下面是尝试生成 PDF 的代码

def make_pdf(student):
    entry = Transaction.objects.filter(student=student)
    credits = entry.filter(t_type='C')
    debits = entry.filter(t_type='D')
    c_count = entry.filter(t_type='C').count()
    d_count = entry.filter(t_type='D').count()
    e_count = entry.count()
    name = student.name
    context = {
        'entries':entry,
        'student':student,
        'credits' : credits,
        'debits':debits,
        'c_count': c_count,
        'd_count': d_count,
        'e_count': e_count,
        'name':name
    }
    return render_to_pdf('payment/statement.html', context)

render_to_pdf 函数在不同的文件中定义如下:

from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template

from xhtml2pdf import pisa

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html  = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

我已经删除了大部分回溯数据以消除混乱,以便您在执行以下代码行时可以看到实际错误

pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1", 'ignore')), 结果)

文件“C:\Users\EliteBook\Desktop\Virtual_Environment\app\lib\site-packages\reportlab\platypus\tables.py”,第 265 行,在 init raise ValueError("%s 数据错误 - 数据中有 %d 行,但行高有 %d" % (self.identity(),nrows, len(rowHeights))) ValueError:单元格(0,0)包含 “size=x”数据错误 - 数据为 16 行,但行高为 15

此链接显示我希望转换为 pdf 的 html 网站,我还附上了 HTML 文件

【问题讨论】:

    标签: django python-3.x reportlab pisa


    【解决方案1】:

    似乎有两个主要原因:

    1. 您的查询集可能不会产生任何可迭代的值 - 请检查。

    1. 如果您在一个页面中有多个表格,那么您的一个表格的格式不适合 pisa e.g. you have a <tr> ...<tr> instead of <tr> ...</tr>. note the closing /

    我解决这个问题的方法是将整个页面拆分为部分(每个表都作为部分)并在浏览器中一一加载。

    您很可能识别出导致错误的表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-04
      • 2017-12-19
      • 2014-03-19
      • 2022-03-07
      • 2021-09-21
      相关资源
      最近更新 更多