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

106 Views Asked by At

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.

1

There are 1 best solutions below

0
On

Sorry for this being rather a late reply, I just happened to find this post today while looking for a solution myself.

I was trying to do exactly this, and getting myself tied in all kinds of knots trying to scale an SVG image (it's not at all straightforward).

Then I found that the reportlab drawing has a renderScale property (which I cannot find a mention of in the docs).

So for your example above I think this would scale it by half:

drawing.renderScale = 0.5

This has worked nicely in my project.