Hi,
I've been using PDFSharp recently and needed to pull in some dynamic text and add it to the end of an existing PDF. The problem I had was knowing how much height the last piece of text used. I'm using
XTextFormatter.DrawString and making it word wrap by providing plenty of height for it to work with.
Code:
var rect = new XRect(textMargin, y, page.Width - (textMargin * 2), page.Height - y);
textFormatter.DrawString(partText, font, XBrushes.Black, rect, XStringFormats.TopLeft);
As you can see I am giving
DrawString the rest of the page to work with.
I've come up with a nasty little hack to work out the height the most recent
DrawString used by writing a wrapper around XTextFormatter with a bit of reflection code to get at the private
List<Block> blocks field
Code:
public XSize GetDrawingSize()
{
var blocks = GetType()
.BaseType
.GetField("blocks", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(this) as IList;
double x = 0.0, y = 0.0;
if (blocks != null)
{
foreach (var block in blocks)
{
var location =
(XPoint) block
.GetType()
.GetField("Location", BindingFlags.Instance | BindingFlags.Public)
.GetValue(block);
var width =
(double) block
.GetType()
.GetField("Width", BindingFlags.Instance | BindingFlags.Public)
.GetValue(block);
x = Math.Max(x, location.X + width);
y = Math.Max(y, location.Y);
}
}
return new XSize(x, y + GetFontLineHeight());
}
I've had to use a foreach loop rather than Linq because the
Block class is private to the
XTextFormatter class.
Here is the code for
GetFontLineHeight ...
Code:
protected double GetFontLineHeight()
{
var font = GetType()
.BaseType
.GetField("font", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(this) as XFont;
return font.GetHeight(_gfx);
}
It's very hackety hacky, but it does work.
What I'd like to do is provide a fix to PDFSharp, probably in the form of a MeasureString method within the XTextFormatter class. I think I'd just refactor DrawString and MeasureString to use the same block/layout code, the difference being whether or not to Draw the string.
So, my question is - How do I contribute code to PDFSharp?