Python – How to use renderPM in a temp file to convert a SVG

Question:

I need to convert a svg image to a png using renderPM.

I’m using a library to generate a payment qr code and it produces a SVG output inside of a temp file.

But when i try to convert the svg i got this error:
my error

the code:

    with tempfile.TemporaryFile(encoding='utf-8', mode='r+') as temp:
        order_bill.as_svg(temp)

        temp.seek(0)
        drawing = svg2rlg(temp)
        drawing.scale(300 / 72, 300 / 72)
        renderPM.drawToFile(drawing, temp, fmt='PNG', dpi=300)
        order.qr_bill.save('qrbill.png', File(temp), save=True)

Thank you very much for your help 🙂

I’ve tried to convert it using cairo but it does not work on my machine (m1 max macbook)

Asked By: Dragos

||

Answers:

To convert an SVG image to a PNG using renderPM, you can use the following code:

import cairo
import svg2rlg
from renderPM import drawToFile
    
    with tempfile.TemporaryFile(encoding='utf-8', mode='r+') as temp:
        order_bill.as_svg(temp)
        temp.seek(0)
        drawing = svg2rlg(temp)
        drawing.scale(300 / 72, 300 / 72)
    
        # Create a Cairo context
        ctx = cairo.Context(cairo.ImageSurface(cairo.FORMAT_ARGB32, int(drawing.width * 3), int(drawing.height * 3)))
        ctx.scale(3, 3)
        # Render the drawing
        drawToFile(drawing, ctx)
        # Finalize the image
        surface.flush()
        # Save the image
        with open('qrbill.png', 'wb') as image_file:
            image_file.write(surface.get_data())
Answered By: Mohammed Foud
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.