【问题标题】:In Itext 7 find width of string requiring multiple fonts在 Itext 7 中找到需要多种字体的字符串宽度
【发布时间】:2017-04-12 15:29:46
【问题描述】:

使用 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 方法,我需要遍历字符串的各个部分,并根据所使用的字体将每个部分的长度相加。寻找如何做到这一点的例子。

【问题讨论】:

    标签: pdf fonts itext7


    【解决方案1】:

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

    代码如下所示:

    // 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;
    

    【讨论】:

    • 谢谢!比我想象的要简单。也欣赏基于 1000 的宽度和字体大小的解释。
    • 如何知道首选字体?
    • @JoeEltgroth,如果您不知道首选字体,您可以传递任何字符串,甚至是空字符串。首选字体类似于在 HTML 中指定字体系列。如果“首选”字体无论如何都无法呈现所需的字形,将使用另一种字体。但是,如果您的字体提供程序中有“Arial”和“Times New Roman”,并且您将“Arial”设置为首选字体,那么在其他条件相同的情况下,Arial 将具有更高的优先级
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 2020-05-24
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2014-10-04
    相关资源
    最近更新 更多