使用Django打印PDF条形码

问题描述 投票:0回答:1

我正在django中使用render_to_string解析HTML并导出为PDF。

   html = render_to_string("etiquetaTNT.html", {
        'context': context,
        'barcode': b,
        'barcodeimg': barcodeimg,
    })

    font_config = FontConfiguration()
    HTML(string=html).write_pdf(response, font_config=font_config)
    return response

我正在尝试在PDF中插入条形码。我在PNG中生成此条形码。

    br = barcode.get('code128', b, writer=ImageWriter())
    filename = br.save(b)
    barcodeimg = filename

但是模板中的PDF,不显示图像。

    <img class="logo" src="{{barcodeimg}}" alt="Barcode" />

我不知道将文件名保存在所需模板中的方法,也不知道要在PDF中显示,因为会显示任何图像。例如,徽标显示在HTML模板中,而不显示在PDF中。

    <img class="logo" src="{{logo}}" alt="TNT Logo" />

我正在使用的库:

   import barcode
   from barcode.writer import ImageWriter

   from django.http import HttpResponse
   from django.template.loader import render_to_string

   from weasyprint import HTML
   from weasyprint.fonts import FontConfiguration

我不想使用Reportlab,因为我需要呈现HTML,而不是Canvas。

django pdf barcode
1个回答
1
投票

了解问题:

考虑加载网页时会发生什么。最初的请求是在其中加载文档的,然后是后续的请求,以获取图像/其他资产。

[当您想使用weasyprint将一些HTML打印为PDF时,weasyprint必须获取所有其他图像。签出python-barcode文档,br.save(b)只会返回字面意义上的文件名(将保存在当前工作目录中)。因此,您的html将如下所示:

<img class="logo" src="some_filename.svg" alt="Barcode" />

如何获取此内容将取决于您如何设置weasyprint。您可以签出具有自定义网址提取程序的django-weasyprint。但就目前情况而言,weasyprint无法获取此文件。

解决方案

有几种方法可以解决此问题。但这很大程度上取决于您如何部署它。例如,heroku(据我所知)没有可写入的本地文件系统,因此您需要将文件写入到s3之类的外部服务,然后将该URL插入模板中,然后weasyprint将能够获取。但是,我认为在这种情况下,我们可以使用更简单的解决方案。

一个更好的(也许)解决方案

看一下python-barcode文档,看起来您可以使用SVG编写。这很好,因为我们可以将SVG直接插入HTML模板中(并避免获取其他任何资产)。我建议类似以下内容

from io import BytesIO
from barcode.writer import SVGWriter

# Write the barcode to a binary stream
rv = BytesIO()
code = barcode.get('code128', b, writer=SVGWriter())
code.write(rv)

rv.seek(0)
# get rid of the first bit of boilerplate
rv.readline()
rv.readline()
rv.readline()
rv.readline()
# read the svg tag into a string
svg = rv.read()

现在,您只需要将该字符串插入模板即可。只需将其添加到您的上下文中,并按如下所示进行渲染:

{{svg}}
© www.soinside.com 2019 - 2024. All rights reserved.