How to draw image from raw bytes using ReportLab?

北城余情 提交于 2019-12-11 05:16:27

问题


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

回答1:


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
img = ImageReader(io.BytesIO(raw_image_bytes))
page.drawImage(image, ...)


来源:https://stackoverflow.com/questions/40966401/how-to-draw-image-from-raw-bytes-using-reportlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!