We are creating PDF documents on the fly from the database using PDFsharp.
I need to know the best way to calculate the height of the text area based on the font use
In case anyone still wants to find an answer, I've implemented a reasonably easy-to-understand method to find out the height of the resulting text.
Public Function PrintString(text As String, ft As XFont, rect As XRect, graph As XGraphics, b As SolidBrush, Optional tf As XTextFormatter = Nothing) As Integer
If Not IsNothing(tf) Then
tf.DrawString(text, ft, b, rect)
Else
Dim drawLeft As New XStringFormat
drawLeft.Alignment = XStringAlignment.Near
graph.DrawString(text, ft, b, rect, drawLeft)
End If
Dim width As Double = graph.MeasureString(text, ft).Width
Dim multiplier As Integer = 0
While width > 0
multiplier += 1
width -= rect.Width
End While
Dim height As Double = (graph.MeasureString(text, ft).Height) * multiplier
Return height
End Function
Explaining the code:
First, print the text. I included an Optional XTextFormatter called tf because I use either XGraphics or XTextFormatters interchangeably in my application.
Then, calculate how long the text was by MeasureString().Width.
Then, calculate how many lines of text there were. This is done by dividing the total length of the text found earlier by the width of the provided rectangle (box) where the tax is printed. I did it with a while loop here.
Multiply the height of the text (using graph.MeasureString().Height) by the number of lines there were. This is the final height of your text.
Return the height value. Now, calling the PrintString() function will print the text provided out while returning the height of the printed text afterward.
The PdfSharp.Drawing.XGraphics object has a MeasureString method that returns what you require.
var pdfDoc = new PdfSharp.Pdf.PdfDocument();
var pdfPage = pdfDoc.AddPage();
var pdfGfx = PdfSharp.Drawing.XGraphics.FromPdfPage(pdfPage);
var pdfFont = new PdfSharp.Drawing.XFont("Helvetica", 20);
while (pdfGfx.MeasureString("Hello World!").Width > pdfPage.Width)
--pdfFont.Size;
pdfGfx.DrawString("Hello World!", pdfFont
, PdfSharp.Drawing.XBrushes.Black
, new PdfSharp.Drawing.XPoint(100, 100));
This should help you. Please consider that I didn't test this code as I wrote it on the fly in order to help. It might contain some compile-time errors, but you may get the idea.