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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With