如何使用PdfSharp库测量文本长度

Mor*_*ori 5 pdf pdfsharp

我需要测量PDF中的文本长度,如果长度超过一定量,则换行.我已经在使用PdfSharp库了.

我已经使用以下代码来确定文本的长度.

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();
}
Run Code Online (Sandbox Code Playgroud)

据我所知,我很依赖于分辨率和dpi转换Height和类的Width属性Size到毫米.但根据PdfSharp的团队在这篇文章中回答"PDF文件是没有DPI的矢量文件".

所以我对使用这个库测量文本长度的正确方法感到困惑.

Je *_*not 7

PDF文件没有像素,PDF文件没有DPI.

带有PDFsharp的标准单位是分数.每英寸有72个点.

您可以使用点,毫米,厘米,英寸等文本的长度...
您可以使用点,毫米,厘米,英寸等页面的宽度...

XTextFormatter类可以为您做简单的换行:http://www.pdfsharp.net/wiki/TextLayout-sample.ashx

此示例演示如何调用MeasureString:
http://www.pdfsharp.net/wiki/Graphics-sample.ashx#Show_how_to_get_text_metric_information_19
使用正确的方法MeasureString与XGraphics对象,你会得到与文本尺寸的XSIZE对象-没有像素,但mm,cm,inch,point,...

使用MigraDoc进行复杂文本格式的换行.