我有一个程序,可以在 C# 中使用 PDFsharp 手动生成 PDF。虽然它相当乏味,但我必须使用它并且即将完成任务。只剩下一个问题了。
问题:我想知道如何找出 Arial 中给定字体大小的给定字符的宽度。
我无法想出更精确的文本换行方法。现在,我们定义一个框的宽度(以像素为单位),然后继续在该框中写出一个字符串。我只是猜测盒子里可以容纳的绳子的最大长度,并且时不时会出现一些视觉上的奇怪现象。
有什么帮助吗?
谢谢
I have a program that is manually generating a PDF using PDFsharp in C#. Although it is rather tedious I have to use it and am nearing completion of the task. Only one issue remains.
Problem: I am wondering how I can find out what the width of a given char is for a given font size in Arial.
I am having trouble coming up with a more precise text wrapping method. Right now one defines a width of box in pixels and then proceeds to write out a string in that box. I kinda just guess at the max length of the string that can fit in the box and there are some visual oddities that crop up from time to time.
Any help?
Thanks
发布评论
评论(3)
从你的问题中我不确定你是否想要一种专门使用 PDF# 来测量字符串大小的方法,或者只是一种通用方法。
在一般的.Net中,您可以使用
的 >MeasureText
方法TextRenderer
类(来自 Windows 表单):这将返回一个
Size
实例将包含Width=12, Height=2
。I'm not sure from your question whether you want a way to measure the size of a string specifically using PDF#, or just a generic way.
In general .Net, you can use the
MeasureText
method of theTextRenderer
class (from Windows forms):This will return a
Size
instance that will containWidth=12, Height=2
.在带有字距调整等的 True Type 字体时代,没有单一的字符宽度。
字符串“VA”的宽度可能小于字符串“V”和“A”的宽度之和。
如果单个字符是一个起点,则总结宽度 - 但最后您必须测量完整的字符串。
PDFsharp 包含执行此换行操作的 XTextFormatter 类(带有完整源代码)。它可以适应特定的要求。
它使用 gfx.MeasureString(token, this.font).Width 来测量字符串的宽度。
In the days of True Type fonts with kerning etc. there is not a single character width.
The width of the string "VA" is probably less then the sum of the widths of the strings "V" and "A".
Summing up the widths if individual characters is a starting point - but finally you have to measure the complete string.
PDFsharp includes the class XTextFormatter (with full source code) that does this line wrapping. It can be adapted for specific requirements.
It uses
gfx.MeasureString(token, this.font).Width
to measure the width of a string.XGraphics.MeasureString(string s, Font f) 就可以了。
XGraphics.MeasureString(string s, Font f) does the trick.