string-pixel-width icon indicating copy to clipboard operation
string-pixel-width copied to clipboard

Using pdfkit

Open techtonik opened this issue 8 years ago • 7 comments

Maybe this will help to get width in different fonts. https://github.com/badges/shields/blob/105e383d93a4a333c2a7ee8038a492c8071f14a5/lib/measure-text.js

UPDATE (20180901): Update link to measure-text.js with archived copy. The code was replaced in https://github.com/badges/shields/commit/cc9a6db853be

techtonik avatar May 01 '17 20:05 techtonik

@techtonik Thanks, this looks good, but I am not sure, how about rendering speed. Do you have any experience with speed? It looks like pdfkit is using its own rendering, that could be fast (faster than rendering into headless browser).

adambisek avatar May 02 '17 15:05 adambisek

No, I haven't measured performance. Was looking for alternative library without PDF in its name.

techtonik avatar May 03 '17 01:05 techtonik

You can use the library PDFKit uses internally: https://github.com/foliojs/fontkit

Code for measuring string width would be as follows:

var fontkit = require('fontkit');

var font = fontkit.openSync('/path/to/font.ttf');

function getStringWidth(str, useKerning) {
    if (useKerning) {
        return font.layout(text).positions.reduce((widthSum, glyphPosition) => widthSum + glyphPosition.xAdvance, 0);
    }
    return font.glyphsForString(str).reduce((widthSum, glyph) => widthSum + glyph.advanceWidth, 0));
}

aquelehugo avatar Aug 22 '18 19:08 aquelehugo

Thanks for your advice. Will look at this. But, one of the prerequisities when this package has been developed was speed. I am not sure that manipulating with PDF would be fast enough.

adambisek avatar Aug 24 '18 14:08 adambisek

It doesn't use PDF, it is the library for font loading only. I don't know how you would get the glyphs width in pixels exactly though, maybe you can get it from the pdfkit's implementation. fontkit only provides width for glyphs in their original scale. That's enough for me because I just need the proportions. Of course it will not be faster than your method which just access arrays, but there's a point you missed: kerning. Width for 'Vo' is not the same as the sum for 'V' and 'o' separately, for instance. The 'o' is rendered closer to the 'V' to improve readability.

aquelehugo avatar Aug 24 '18 14:08 aquelehugo

Wow, sounds very promising! Will dive into when I have a little bit time!

adambisek avatar Aug 24 '18 14:08 adambisek

Make sure to checkout https://github.com/badges/shields/issues/1379 for performance discussion.

techtonik avatar Sep 01 '18 07:09 techtonik