pythonqr-codereportlabplatypus

Use QrCodeWidget (or PlotArea) with platypus


My django app is using a multi-frames reportlab pdf report in witch I would like to add some barcodes/qr-codes.

The problem I have is that every object I add to my layout have to be a Flowable. So the question would be as to cast a PlotArea (mother class of QrCodeWidget) as Flowable.

If we have an answer here the error message we can get if we add the QrCodeWidget as

AttributeError: QrCodeWidget instance has no attribute 'getKeepWithNext'

Solution

  • Ok, I made my own Flowable, it was simpler than I taught.

    It's as simple as doing it on a canva with this API.

    from reportlab.platypus import Flowable
    from reportlab.graphics.barcode import qr
    from reportlab.graphics import renderPDF
    from reportlab.graphics.shapes import Drawing
    
    class QRFlowable(Flowable):
        # usage : 
        # story.append(QRFlowable("http://google.fr"))
        def __init__(self, qr_value):
            # init and store rendering value
            Flowable.__init__(self)
            self.qr_value = qr_value
    
        def wrap(self, availWidth, availHeight):
            # optionnal, here I ask for the biggest square available
            self.width = self.height = min(availWidth, availHeight)
            return self.width, self.height
    
        def draw(self):
            # here standard and documented QrCodeWidget usage on
            # Flowable canva
            qr_code = qr.QrCodeWidget(self.qr_value)
            bounds = qr_code.getBounds()
            qr_width = bounds[2] - bounds[0]
            qr_height = bounds[3] - bounds[1]
            w = float(self.width)
            d = Drawing(w, w, transform=[w/qr_width, 0, 0, w/qr_height, 0, 0])
            d.add(qr_code)
            renderPDF.draw(d, self.canv, 0, 0)