[Python] Scaling a figure to fit in a pdf page using reportlab, and svglib

Discussão em 'Python' iniciado por Stack, Janeiro 3, 2025.

  1. Stack

    Stack Membro Participativo

    I stumbled on this code to generate a PDF with a plot in it without saving the plot as a file.

    I am now trying to scale the svg before adding it to the PDF so it fits the page (without changing the figsize argument through matplotlib).

    from reportlab.graphics import renderPDF
    from reportlab.lib.pagesizes import LETTER
    from reportlab.pdfgen.canvas import Canvas
    from io import BytesIO

    from svglib.svglib import svg2rlg

    def one_page_pdf(file_name, figs, text="Default"):
    canvas = Canvas(filename=file_name, pagesize=(LETTER[1], LETTER[0]))
    img_data = BytesIO()
    figs.savefig(img_data, format="svg")
    # figs.set_size_inches(6, 6)
    img_data.seek(0)

    drawing = svg2rlg(img_data)
    renderPDF.draw(drawing, canvas, 10, 100)
    canvas.drawString(10, 50, text)
    canvas.showPage()
    canvas.save()


    How can I do it properly?

    I tried changing the size of the svg using svgutils but this didn't go well.

    Continue reading...

Compartilhe esta Página