PDFsharp & MigraDoc Foundation
https://forum.pdfsharp.net/

Keep text within a rectangle with PDFsharp
https://forum.pdfsharp.net/viewtopic.php?f=2&t=2747
Page 1 of 1

Author:  fullingdale [ Thu Feb 27, 2014 10:39 am ]
Post subject:  Keep text within a rectangle with PDFsharp

I have a box which is 10cm by 10cm in which I am putting a string of text.

I am using the formatter to word-wrap, which works perfect.

However, when I have a lot of text, it seems to ignore the height of the rectangle and spills out below it.

Is there a way to stop this?

Anything which does not fit in the box, should simply not be visible on the PDF.

Author:  Thomas Hoevel [ Thu Feb 27, 2014 10:54 am ]
Post subject:  Re: Keep text within a rectangle with PDFsharp

I presume the question is about PDFsharp.

How do you wrap the text? I presume it's XTextFormatter.

If you use XTextFormatter: copy the source code to your project and make the class stop adding lines when the allowed space was already filled.

XTextFormatter is just a quick shot to get you started, it's not the ultimate formatter.

Author:  fullingdale [ Thu Feb 27, 2014 2:36 pm ]
Post subject:  Re: Keep text within a rectangle with PDFsharp

I've made the changes and it works a treat, thank you.
For the benefit of anyone wanting to make a similar change, I altered the CreateLayout method; removing the following lines of code:
Code:
if (y > rectHeight)
{
   block.Stop = true;
   break;
}

And following the if (block.Type == BlockType.LineBreak) then..else (in the same method), I first added the following, which met the requirement that I initially had, to ensure that the text did not flow beyond the boundary of the rectangle.
Code:
if (y < rectHeight) continue;
block.Stop = true;
break;

I have since extended this a little further, so that in any instance where the text "would" have overflowed the rectangle, it will not allow the overflow and will append "[...]" in place of the last word, on the last line...
Code:
if (y < rectHeight) continue;
if (idx < count)
{
    int lastidx = idx;
    while (lastidx > 0 && this.blocks[lastidx].Type == BlockType.LineBreak)
    {
        lastidx--;
    }
    this.blocks[lastidx].Text = "[...]";
}
block.Stop = true;
break;

Note that I replaced the last word, rather than appending to it, because I wanted to avoid making the text potentially overflow the right edge of the rectangle, and don't have the time right now to work out how to ensure that this doesn't ever occur

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/