python - 如何使用Report Lab 的 Canvas drawImage() 插入图像?

标签 python pdf-generation reportlab drawimage

我希望使用报告实验室的 pdfgen 来扩展工具的功能,该工具目前仅使用以下方式绘制字符串:

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

和 json;

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

因此,为了绘制图像而不是字符串,我执行了以下操作;

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"]]
)

将 json 更新为;

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

drawImage的调用有问题吗?根据文档,它看起来是正确的,但它没有进入 drawImage 因为我尝试记录函数获取的参数,但我什么也没得到。

最佳答案

我使用drawImage的方法没有任何问题,并且以下代码目前使用成功;

# 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)

以及对应的json来指定图片文件名;

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

关于python - 如何使用Report Lab 的 Canvas drawImage() 插入图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14890319/

相关文章:

Python打包: build requirements in pyproject. toml VS setup_requires

python - 如何转换非常大的数据框以获取所有列中的值的计数(不使用 df.stack 或 df.apply)

Python:使用 %x(语言环境)格式化的日期与预期不符

angular6 - 如何将角度页面导出为多页 pdf

python - Reportlab:如何向 pdf 文件添加页脚

pdf-generation - 如何在ReportLab的PDF输出中的分页符上重复表格列标题

python - 如何让 matplotlib 在同一窗口中绘制图像序列

iOS 创建 PDF 时添加链接

html - Pdf 使用 UIViewPrintFormatter 从 Html 创建,不显示本地镜像

python - 报告实验室低性能