How to measure the text length using PDFsharp library
Asked Answered
L

1

10

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.

Landin answered 20/10, 2014 at 12:47 Comment(0)
T
11

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)

Typography answered 20/10, 2014 at 13:0 Comment(2)
What's the difference between DPI and PPI exactly?Millisent
Point is a unit. You can use line widths like 0.5 point or 0.25 points and font sizes like 8.5 points. See Wikipedia: en.wikipedia.org/wiki/Point_(typography)Typography

© 2022 - 2024 — McMap. All rights reserved.