【问题标题】:Apply alignments on Reportlab SimpleDocTemplate to append multiple barcodes in number of rows在 Reportlab SimpleDocTemplate 上应用对齐以在行数中附加多个条形码
【发布时间】:2016-12-18 02:01:15
【问题描述】:

我正在使用 Reportlab SimpleDocTemplate 创建一个 pdf 文件。我必须逐行编写(绘制)多个图像,以便我可以调整文件中的许多图像。

class PrintBarCodes(View):

     def get(self, request, format=None):
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment;\
        filename="barcodes.pdf"'

        # Close the PDF object cleanly, and we're done.
        ean = barcode.get('ean13', '123456789102', writer=ImageWriter())
        filename = ean.save('ean13')
        doc = SimpleDocTemplate(response, pagesize=A4)
        parts = []
        parts.append(Image(filename))
        doc.build(parts)
        return response

在代码中,我已将单个条形码打印到文件中。并且,输出显示在图像中,如下所示。

但是,我需要画一些条形码。如何在绘制到pdf文件之前缩小图像尺寸并以行方式调整?

【问题讨论】:

  • 下面的答案是你的意思吗?
  • 是的。谢谢@B8vrede

标签: python django barcode reportlab


【解决方案1】:

正如您的问题表明您需要灵活性,我认为最明智的方法是使用Flowable。条形码通常不是一个,但我们可以很容易地make it one。通过这样做,我们可以让 决定每个条形码的布局中有多少空间。

所以第一步 Barcode Flowable 看起来像这样:

from reportlab.graphics import renderPDF
from reportlab.graphics.barcode.eanbc import Ean13BarcodeWidget
from reportlab.graphics.shapes import Drawing
from reportlab.platypus import Flowable

class BarCode(Flowable):
    # Based on https://stackoverflow.com/questions/18569682/use-qrcodewidget-or-plotarea-with-platypus
    def __init__(self, value="1234567890", ratio=0.5):
        # init and store rendering value
        Flowable.__init__(self)
        self.value = value
        self.ratio = ratio

    def wrap(self, availWidth, availHeight):
        # Make the barcode fill the width while maintaining the ratio
        self.width = availWidth
        self.height = self.ratio * availWidth
        return self.width, self.height

    def draw(self):
        # Flowable canvas
        bar_code = Ean13BarcodeWidget(value=self.value)
        bounds = bar_code.getBounds()
        bar_width = bounds[2] - bounds[0]
        bar_height = bounds[3] - bounds[1]
        w = float(self.width)
        h = float(self.height)
        d = Drawing(w, h, transform=[w / bar_width, 0, 0, h / bar_height, 0, 0])
        d.add(bar_code)
        renderPDF.draw(d, self.canv, 0, 0)

然后回答您的问题,现在将多个条形码放在一页上的最简单方法是使用Table,如下所示:

from reportlab.platypus import SimpleDocTemplate, Table
from reportlab.lib.pagesizes import A4

doc = SimpleDocTemplate("test.pdf", pagesize=A4)

table_data = [[BarCode(value='123'), BarCode(value='456')],
              [BarCode(value='789'), BarCode(value='012')]]

barcode_table = Table(table_data)

parts = []
parts.append(barcode_table)
doc.build(parts)

哪些输出:

【讨论】:

  • 这个可以扩展到code39吗?它没有小部件 afaik
猜你喜欢
  • 2012-11-26
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
相关资源
最近更新 更多