[reportlab-users] set canvas dimensions to match text object

gordon wgordonw1 at gmail.com
Fri Jun 23 09:46:53 EDT 2017


Good Afternoon,

I am trying to create a pdf canvas that is the minimum dimensions to fully
contain a text object containing arbitrary text of arbitrary lines.

I have gotten close but I think I am missing something in my calculation
for the height because my calculated heights are larger than the actual
display result.

Any tips on how to make my height calculation more accurate?

Here is my render code:

```
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfgen.canvas import Canvas


lines = [
    "Lorem ipsum dolor sit amet",
    "laboramus cu eos, sit intellegat sadipscing",
    "Ut summo reprimique eum",
    "propriae concludaturque",
]


font_size = 16
font_name = 'Helvetica'
face = pdfmetrics.getFont(font_name).face
ascent = (face.ascent * font_size) / 1000.0
descent = (face.descent * font_size) / 1000.0
line_height = ascent - descent
line_spacing = font_size * 1.2

line_widths = []
for line in lines:
    width = pdfmetrics.stringWidth(line, font_name, font_size)
    line_widths.append(width)

text_width = max(line_widths)
text_spacing = line_spacing * (len(lines) - 2)
text_height = line_height * len(lines) + text_spacing
canvas = Canvas("output.pdf", pagesize=(text_width, text_height))

x = 0
y = text_height - line_height
text = canvas.beginText(x, y)
text.setFont(font_name, font_size)
text.setLeading(line_spacing)
for line in lines:
    width_offset = (text_width - pdfmetrics.stringWidth(line, font_name,
font_size)) / 2
    text.setTextOrigin(width_offset, text.getY())
    text.textLine(line)

canvas.drawText(text)
canvas.showPage()
canvas.save()
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://pairlist2.pair.net/pipermail/reportlab-users/attachments/20170623/d187b0aa/attachment.html>


More information about the reportlab-users mailing list