Calculate ideal font size so text can fit into cell


I am a programmer and I have printing code that draws grid on the paper.

Grid has 4 columns, and they have equal horizontal length. Height of the cell is one tenth of the paper size and is fixed.

Total number of rows is unknown but I know for a fact that there will be at least one row, and that cells will have fixed dimensions.

Maximum number of characters that can fit into cell is 50.

User can choose the paper size on which printing will be done and there I face a problem:

Since the cell dimensions depend on paper size, I do not know how to calculate font size so text can fit into cell.

I have asked for help on StackOverflow but failed, and have tried to find a mathematical formula but that solution didn't work for every case.

I apologize for asking here, but I am desperate at the moment. If further info is required please ask and I will update my post.

Thank you.

5/23/2017 12:40:00 PM

Generally a programming language will have a device context which will allow you to draw some example text and then measure it's width and height. For example in python, using wxPython GUI toolkit:

import wx
dc = wx.ScreenDC()
#yourFont =  wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, True)
w,h = dc.GetTextExtent('X') 

Regardless of which tools you are using the requirements are generally the same. You need to know your desired font size and desired cell padding:

cell_height = padding_top + text_height + padding_bottom

where units are generally pixels and text_height is a f(fontSize).

Generally it is not advisable to size fonts based on width unless you are willing to wrap the text. Use a '...' or something to cut short long text if you can't use a new line.

Don't write your own text wrapping code either. Again, in python:

import textwrap
a = "This sentence is less than 50 characters"
widthInChars = 20
lines = textwrap.wrap(a,widthInChars)

Now you have a relationship between font size, line spacing, padding, and cell size.

7/13/2014 3:16:00 PM