Is there a way to limit a DrawString
to a specified rectangle? I want the string to be truncated (preferrably with an ellipsis "...") if it doesn't fit.
From other questions on StackOverflow and trial-and-error I've been able to get PDFsharp to wrap a text, but only if it contains whitespace .
var stringToPrint = "m m m m m m m m m m m m";
var temp = gfx.MeasureString(stringToPrint, font);
var rect = new XRect(new XPoint(leftMargin + leftPush, topMargin + topPush),
new XPoint(leftMargin + page.Width / 2, topMargin + temp.Height));
var tf = new XTextFormatter(gfx);
gfx.DrawRectangle(XBrushes.Red, rect);
tf.DrawString(stringToPrint, font, XBrushes.Black, rect, topLeftStringFormat);
The code above works, but as I said only if the string contains whitespace. On a string like var stringToPrint = "mmmmmmmmmmmm";
it writes the whole string and continues past the rightside edge outside the rectangle.
PDFsharp is open source, so there always is a way.
The XTextFormatter
class is provided as a sample to get you started. You can change that class to add an ellipsis or break at other characters.
PDFsharp was created as a tool for MigraDoc. Maybe MigraDoc is a better solution for you if you do not want to deal with line-breaks and page-breaks. The XTextFormatter
class intentionally lacks a lot of features you find in MigraDoc.
What I ended up doing was implementing a method for limiting the length of stringToPrint
so that it will fit inside the rectangle. I can do that by measuring the width of the contents and then truncating one character a time until it fits.
private static string GetFittedStringToPrint(XGraphics gfx, XFont font, XRect rect,
string input)
{
var output = input;
var stringMeasurement = gfx.MeasureString(input, font);
if (stringMeasurement.Width > rect.Width)
{
var inputMinusOneChar = input;
do
{
inputMinusOneChar = inputMinusOneChar.Substring(0, inputMinusOneChar.Length - 1).Trim();
stringMeasurement = gfx.MeasureString(inputMinusOneChar + '…', font);
} while (stringMeasurement.Width > rect.Width);
output = inputMinusOneChar + '…';
}
return output;
}
The call to the method would then be
stringToPrint = GetFittedStringToPrint(gfx, font, rect, stringToPrint);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.