Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate text height based on available width and font?

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 used and the available width.

I need to know the height so I can process page breaks when required.

like image 473
c00ke Avatar asked May 23 '09 10:05

c00ke


People also ask

How do I calculate text height?

Multiply the drawing scale factor by the desired text output height to determine the height of the text objects in the drawing. Using the drawing scale factor of 48 and a desired text height of 3/16” for the output, you would take 48 x 0.1875 to get a final text height of 9.

How do you calculate line height from font size?

For the optimal readability and accessibility, you should go with140 – 180% line height (this is the space around a line of text). This means if your font size is 16pt, your line height should be at least 16 x 1.4 = 22.4pt (140%), or 16 x1. 8= 28.8pt (180%) maximum value.

Is font size same as line height?

Sets line height to be equal to a multiple of the font size. If your font size is 10px, your line height will be 10px, 18px, and 20px, respectively. Sets line height as a percentage of the font size of the element. If your font size is 10px, your line height will be 3px, 5px, and 11px respectively.


2 Answers

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.

like image 159
Will Marcouiller Avatar answered Sep 30 '22 02:09

Will Marcouiller


In .NET you can call Graphics.MeasureString to find out how large the drawn text is going to be.

Right, but when using PDFsharp you call XGraphics.MeasureString.

like image 26
I liked the old Stack Overflow Avatar answered Sep 30 '22 02:09

I liked the old Stack Overflow