Search code examples
pythonpdf-generationreportlabdrawimage

How do you insert an image using Report Lab's canvas drawImage()?


I'm looking to expand the functionality of a tool using report lab's pdfgen which currently only draws strings using;

if json_data[definition["field"]] != "":
    c.drawString(
        definition["x"] * cm,
        definition["y"] * cm,
        json_data[definition["field"]]
)

and the json;

{
    "field":"name",
    "x":1.8,
    "y":10
},

So to draw images instead of strings I did the following;

if json_data[definition["field"]] != "":
    if definition.has_key("image"):
        c.drawImage(
            os.path.join(os.getcwd(), "images", "successIcon.gif"),
            definition["x"] * cm,
            definition["y"] * cm,
            width=16, height=16,
        )
    else:
        c.drawString(
            definition["x"] * cm,
            definition["y"] * cm,
            json_data[definition["field"]]
)

with the json updated to;

{
    "field":"name",
    "x":1.8,
    "y":10,
    "image":"name"
},

Is there something wrong with that call to drawImage? It looks correct according to the docs but it doesn't make it to drawImage because I've tried to log the args which the function gets & I'm getting nothing.


Solution

  • There wasn't anything wrong with the method I used to use drawImage and the following code is currently in use successfully;

    # If we have an image attribute
    if definition.has_key("image"):
        if str(json_data[definition["field"]]) == 'True':
            # need to replace this with url on attribute
            filename = os.path.join(
                os.getcwd(),
                "static",
                "images",
                definition["image"]
            )
            c.drawImage(filename, definition["x"] * cm, definition["y"] * cm, 10, -10)
    

    And the corresponding json to specify the image filename;

    {
        "field":"name",
        "x":1.66,
        "y":19.45,
        "image":"image.jpg"
    },