Android Code Snippet PDF: Calculate chars per line/lines per page

This snippet is about Erel's example: https://www.b4x.com/android/forum/threads/printing-and-pdf-creation.76712/

We know how the dimensions of a DIN-A4 document is (Width 595 and Height 842)

B4X:
pdf.StartPage(595, 842) 'A4 size

If you want to print on a document you need to know:

- how many chars you can print in one line and
- how high a char (a line) will be
- how many lines you can print

B4X:
Dim TE As String 'put the text here
Dim StringWidth, StringHeight,WidthPerChar As Float
Dim CharsPerLine, LinesPerDocument,LinesNeeded,  A4Width, A4Height As INT
Dim LineOffset As Int = 5

A4Width=595
A4Height=842

Dim pdf As PdfDocument
pdf.Initialize
TE="Hello this is a text"
CharsCount=TE.Length

pdf.StartPage(A4Width, A4Height) 'A4 size
StringWidth=pdf.Canvas.MeasureStringWidth(TE,Typeface.DEFAULT_BOLD, TS )
StringHeight=pdf.Canvas.MeasureStringheight(TE,Typeface.DEFAULT_BOLD, TS +LineOffset)
WidthPerChar=StringWidth/CharsCount
CharsPerLine=A4Width/WidthPerChar-2
LinesPerDocument=A4Height/StringHeight
LinesNeeded=CharsCount/CharsPerLine+1

StringWidth: The total needed width of the complete text
StringHeight: The height of each char plus an offset (otherwise there is no line spacing)
WidthPerChar: The width per single char
CharsPerLine: How many chars you can print in one line minus an offset/border
LinesPerDocument: How many lines fit on a page depending on the textsize and spacing
LinesNeeded: How many lines needed depending on the text lenght

So if you have a short text: Just print the single line. If you have a long text you now know how many chars you can print in one line so just loop through the complete text and change the y position to the next line after CharsPerLine is reached.

Play arround with the values. If you use mixed fontsizes just add the height after every printed line.


Note: Using the Scale function of the example did not work for me

B4X:
30 / GetDeviceLayoutValues.Scale
 
Top