views:

636

answers:

3

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.

+3  A: 

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

onedozenbagels
+8  A: 

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.

Will Marcouiller
+3  A: 

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.

The best place to ask PDFsharp and MigraDoc Foundation related questions is the PDFsharp forum. The PDFsharp Team will not monitor stackoverflow.com on a regular basis.

PDFsharp Forum:
http://forum.pdfsharp.net/

PDFsharp Team