Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure the text length using PDFsharp library

Tags:

pdf

pdfsharp

I have a requirement to measure the text length in a PDF and wrap the line if the length exceeds a certain amount. I am already using PDFsharp library.

I already used the following code to determine the length of the text.

public static Size MeasureString(string s, Font font)
{
    SizeF result;
    using (var image = new Bitmap(1, 1))
    {
          using (var g = Graphics.FromImage(image))
          {
              result = g.MeasureString(s, font);
          }
     }
     return result.ToSize();
}

As I understood I am pretty dependent of the resolution and dpi to convert Height and Width properties of the Size class to millimeter. But according to the PDFsharp's team answer in this post "PDF files are vector files that have no DPI".

So I am a bit confused about the right way to measure the text length using this library.

like image 295
Mori Avatar asked Oct 20 '14 12:10

Mori


1 Answers

PDF files have no pixels, PDF files have no DPI.

The standard unit with PDFsharp is points. There are 72 points per inch.

You can have the length of the text in points, mm, cm, inch, ...
You can have the width of the page in points, mm, cm, inch, ...

The XTextFormatter class can do simple line-wrapping for you:
http://www.pdfsharp.net/wiki/TextLayout-sample.ashx

This sample shows how to call MeasureString:
http://www.pdfsharp.net/wiki/Graphics-sample.ashx#Show_how_to_get_text_metric_information_19
Use the correct MeasureString method with an XGraphics object and you will get an XSize object with the text dimensions - no pixels, but mm, cm, inch, point, ...

Use MigraDoc for line-wrapping with sophisticated text formatting.

The Wikipedia article on Points: https://en.wikipedia.org/wiki/Point_(typography)

like image 58
I liked the old Stack Overflow Avatar answered Oct 03 '22 05:10

I liked the old Stack Overflow