Search code examples
pythondjangopython-3.xpdf-generationreportlab

How to draw image from raw bytes using ReportLab?


All the examples I encounter in the internet is loading the image from url (either locally or in the web). What I want is to draw the image directly to the pdf from raw bytes.

UPDATE:

@georgexsh Here is my code based on my understanding of your comment below:

def PDF_view(request):
    response = HttpResponse(content_type='application/pdf')

    ...

    page = canvas.Canvas(response, pagesize=A4)
    page.setTitle("Sample PDF")


    image = StringIO(raw_image_bytes) # raw_image_bytes is from external source
    image.seek(0)
    page.drawImage(image, 100, 100 )

    filename = 'document.pdf'
    page.showPage()
    page.save()

    return response

Solution

  • from report lab Image object source code, filelike obj is acceptable, so you could wrap image data with StringIO/io.BytesIO, pass it as filename.


    updated:

    as you're using drawImage method, it needs a ImageReader obj:

    from reportlab.lib.utils import ImageReader
    import io
    image = ImageReader(io.BytesIO(raw_image_bytes))
    page.drawImage(image, ...)