在 Itext 7 中查找需要多种字体的字符串宽度

In Itext 7 find width of string requiring multiple fonts

使用 iText 7 (7.0.2),如何找到包含需要不同字体的字符的字符串的宽度?

例如,在下面的代码中,既有英文字符,也有俄文字符。我想根据 FontProvider 分配给每个字符的字体找到该字符串的宽度。

String s = "Hello world! Здравствуй мир! Hello world! Здравствуй мир!";
FontProvider sel = new FontProvider();
sel.addFont(fontsFolder + "NotoSans-Regular.ttf");
sel.addFont(fontsFolder + "Puritan2.otf");

如果字符串只有可以用一种字体呈现的字符,我可以这样做:

PdfFont font = PdfFontFactory.createFont(fontsFolder + "Puritan2.otf", PdfEncodings.IDENTITY_H, true);
font.getWidth(s, 12f); 

鉴于 FontProvider 本身没有 getWidth 方法,我需要遍历字符串的各个部分,并根据使用的字体将每个部分的长度相加。寻找如何执行此操作的示例。

在非常低的级别上,您确实必须遍历根据每个片段使用的字体分解的原始字符串片段。

代码如下所示:

// Get the strategy that is responsible for splitting. 
// The "FreeSans" argument is the "preferred" font.
FontSelectorStrategy strategy = sel.getStrategy(s, Arrays.asList("FreeSans"));
float totalWidth = 0;
while (!strategy.endOfText()) {
    for (Glyph glyph : strategy.nextGlyphs()) {
        totalWidth += glyph.getWidth();
    }
}
// Division by font unit size, because glyph.getWidth() is a 1000-based value
totalWidth /= 1000;
// Multiplication by font size
totalWidth *= 12;