如何使用 ReportLab 从原始字节绘制图像? [英] How to draw image from raw bytes using ReportLab?

查看:59
本文介绍了如何使用 ReportLab 从原始字节绘制图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上遇到的所有示例都是从 url(本地或网络中)加载图像.我想要的是将图像从原始字节直接绘制到 pdf 中.

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.

更新:

@georgexsh 以下是我根据您对以下评论的理解编写的代码:

@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

推荐答案

来自 report lab Image object source code,filelike obj 是可以接受的,所以你可以用 StringIO 包装图像数据/io.BytesIO,将其作为filename 传递.

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.

更新:

当你使用 drawImage 方法时,它需要一个 ImageReader obj:

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, ...)

这篇关于如何使用 ReportLab 从原始字节绘制图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆