iTextSharp GetWidthPoint() 不包括字母间距

iTextSharp GetWidthPoint() does not include the letter spacing

考虑以下代码:

var path = AppDomain.CurrentDomain.BaseDirectory;
var filePath = Path.Combine(path, "test1.pdf");

using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
using (var document = new Document(new Rectangle(PageSize.A4.Width, PageSize.A4.Height)))
using (var writer = PdfWriter.GetInstance(document, stream))
{

    try
    {

        document.Open();

        const string value = "The quick brown fox";

        for (int i = 0; i < 4; i++)
        {

            var chunk = new Chunk(value);

            chunk.SetCharacterSpacing(i);

            var origin = new Phrase(chunk);
            var paragraph1 = new Paragraph(origin);

            document.Add(paragraph1);

            var widthPoint = chunk.GetWidthPoint();

            Debug.WriteLine(widthPoint);

        }

        writer.CloseStream = false;

    }
    finally
    {
        document.Close();
        stream.Close();
    }

}

我正在尝试将 paragraph/chunk 添加到新 PdfPTable 中的单个 PdfPCell。我们无法控制进入单元格的实际文本,并且文本可能会比可用文本长一点 space。要么文本会分成多行,要么流出单元格并被隐藏。

我们的想法是自动减小文本的字母间距(达到最小值),以尝试减轻被裁剪的文本。基本上应用一个小的负字母间距,直到文本适合。问题是 widthPoint 的值始终相同,无论应用的字母间距如何。生成的 PDF 清楚地显示了不同宽度的文本。

有没有办法用字母间距或容器来计算文本的实际宽度?块/段落是(我会描述为)盒模型类型的元素。也就是说它们填充单元格并且始终具有相同的宽度。

不知道如何进行。

这适用于 iTextSharp 版本 5.5.9.0

简单地说:你是对的。 Chunk.GetWidthPoint()只计算不带字符或字间距的宽度:

virtual public float GetWidthPoint() {
    if (GetImage() != null) {
        return GetImage().ScaledWidth;
    }
    return font.GetCalculatedBaseFont(true).GetWidthPoint(Content, font.CalculatedSize) * HorizontalScaling;
} 

因此,

Is there a way to calculate the actual width of the text with letter-spacing, or it's container?

开箱即用的 iTextSharp 5 提供了 none。但是您可以像这样轻松计算出正确的值:

float WidthWithCharSpacing = chunk.GetWidthPoint() + chunk.GetCharacterSpacing() * (chunk.Content.Length - 1);

您可能正在寻找 GetWidthPointKerned 方法,该方法考虑了字符之间的字距调整。