How to get line breaks in a long text when writing to a pdf using canvas

478 Views Asked by At

I am trying to write long texts (captured through string.xml in the $nameSpeech variable) to a pdf using canvas.drawText, but it does not implement any line breaks, and \n and more do not work. Is this possible anyway using canvas.drawText?

canvas.drawText("This was his speech: $nameSpeech",20F, 200F,title)

I am a rookie with Kotlin and studied several main developer sites, and tried to specify start and end drawText. There is a lot on Java but little on Kotlin. Who can help?

1

There are 1 best solutions below

0
cactustictacs On

Nah, all the Canvas draw methods are fairly low-level operations to draw shapes at particular points, it doesn't do anything fancy with interpreting text as multiline, doing any wrapping etc.

You could break the lines yourself and render each one:

val lines = text.split('\n')
lines.forEachIndexed { i, line ->
    drawText(line, x, y + (lineSpacing * i), paint)
}

lineSpacing is the height of your text - you can get a lot of this by setting your typeface and text size on your Paint and then accessing its functions like getFontSpacing(). There are also helper functions like breakText that can tell you how many characters of a String will fit a given width so you can handle line breaks, stuff like that.

Again, you're doing a lot of the work yourself here, working out widths and adjusting for spacing etc, breaking lines - TextView is a View that already handles all that work, so you could try just using that, and calling its draw method with a Canvas you want it to use. It needs to have been laid out already, if you don't want it to be visible then setting its visibility to INVISIBLE (not GONE) should be ok (I've never actually done it)

Another thing you could try is actually subclassing TextView, so maybe you could set its size internally, have its onDraw method call the superclass one passing your custom canvas, and have it work without needing to be in a layout. If you're new to all this that might be a bit complex (just because it's unfamiliar really) but it's something you could maybe look into!