Jonathan Wood
Jonathan Wood

Reputation: 67175

How to use XTextFormatter to print multiple paragraphs

Both PDFsharp and PdfSharpCore provide the XTextFormatter class. This class is a lifesaver when it comes to printing blocks that require word wrap.

But here's my question: What if I need to print multiple paragraphs? How can I determine where the bottom of the paragraph just printed is?

XTextFormatter.DrawString() returns void, so it doesn't tell me how far down it got. And there are no overloads that accept a new Y position or rectangle. And the only similar property, LayoutRectangle, simply contains the rectangle that I passed to DrawString(). And XTextFormatter has no MeasureString() method.

So how is it possible to print multiple paragraphs, one just below the previous?

Upvotes: 1

Views: 1059

Answers (2)

SomeGuy
SomeGuy

Reputation: 133

Little bit late, but no answer so far.

You you can compute it yourself, example:

foreach (var paragraph in paragraphs)
{
    double maxWidth = 350; // calculate the maximum width of the text

    double maxHeight = ((gfx.MeasureString(gfx, paragraph.Value, font_regular).Width) / maxWidth) * 10;
    

    // new page in case of overflow
    if (y_coordinate + maxHeight + 10 > page.Height - 40)
    {
        page = generator.AddPage(document);
        gfx = generator.CreateGraphics(page);
        y_coordinate = 60;
    }

    // Print Paragraph //
    XRect rect = new(x_coordinate + columnsize + 13, y_coordinate - 10, maxWidth, maxHeight); // define a rectangle that represents the area where the text should be drawn
    XTextFormatter tf = new(gfx);

    tf.Alignment = XParagraphAlignment.Justify;
    tf.DrawString(paragraph.Value, font_regular, XBrushes.Black, rect, XStringFormats.TopLeft);
    
    y_coordinate += maxHeight + 10;
      
}

You can get number of rows, and then you can multiple it with desired offset and add it to y_coordinate variable. I my example, I want to increase y_coordinate by 10 for each new row of text. At the end of iteration, y_coorinate is increased by paragraph text size plus additional 10, to make gap between paragraphs little bit bigger.

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67175

The answer is that this is not supported. Surprisingly, the author of the XTextFormatter class chooses not to expose this information and keeps the current Y position internal to that class.

Fortunately, both PDFsharp and PdfSharpCore are open source. You can download the XTextFormatter code and tweak it to your heart's content. Or you can work from the version in this discussion.

Upvotes: 0

Related Questions