Просмотр исходного кода

Use stand-in fonts for system fonts in Office PDF

System fonts that cannot be embedded used to be stepped over, or squeezed to width alone, which broke monospace code listings. They now get the nearest face of their kind: the screen's substitute, a shipped metric twin, Cousine for monospace families, or the standard font of that kind.

- Stand-ins are drawn at a size that matches the original's average advance (OfficeFonts.widthOf), so Cousine for Consolas is set at about 0.917 of the size.
- planRun now fits only the ink of each fragment, leaving out edge spaces, which a stand-in sets at a different width.
- Spaces inside highlighted spans still draw their highlight box.
- haveFamily now treats a family as installed if it differs from either generic. This fixes Consolas and Times New Roman, which are Chrome's own monospace and serif defaults.
- The display list carries a per-segment size multiple (k), which pdfdraw applies.
- OfficeFonts exposes kindOf, twinOf and widthOf, and recognises "monaco" as monospace.
- README and slides_pdf header comments updated.
Toby Chui 3 недель назад
Родитель
Сommit
3fe80bb0dc

+ 25 - 10
src/web/Office/README.md

@@ -638,7 +638,9 @@ Three answers, tried in that order, per character (`resolveChar`):
    nothing and every reader already has them. Which family was resolved has
    to be measured, not asked: `document.fonts.check()` answers "is it
    loaded" and says yes to any name, so `haveFamily` probes widths against
-   two generics instead.
+   two generics instead — installed means different from *either* one,
+   because a family can be a generic's own default (Consolas is Chrome's
+   monospace on Windows, Times New Roman its serif).
 2. one of the faces the suite ships with itself (`common/fonts`, see
    [the note there](common/fonts/README.md)) — fetched, parsed for glyph
    coverage, and embedded subset to the glyphs the deck actually used. This
@@ -671,15 +673,28 @@ far the ink's centre moves per unit of its height. In Chrome that lands on
 Skia's own figure at every size; a browser that does not synthesize
 measures as nothing, and the PDF follows it.
 
-A system font that is none of the above is stepped over rather than used,
-and the character lands on the shipped face the document's own font stack
-names next. That is the same thing the browser does when a font has no
-glyph, which is why `OfficeFonts.stack()` is on the end of every
-font-family the editor writes. Because a substituted face is not the one
-the line was measured in, each fragment is then squeezed to the width the
-browser gave it (`Tz`), so it cannot push the rest of the line out of
-shape; when the face *is* the one the browser used, the ratio is 1 and
-nothing happens.
+A system font that is none of the above stands in as the nearest face of
+its kind (`standIn`): for a family this machine lacks, the face the screen
+drew it in (`OfficeFonts.substituteOf`); for an installed one, its shipped
+metric twin (Calibri → Carlito), else **Cousine for any monospace family**,
+else the standard font of its kind. The stand-in is drawn at the size that
+gives it the original's average advance (`OfficeFonts.widthOf`), so Cousine
+for Consolas is set at 0.917 of the size — Consolas's width and nearly its
+x-height — instead of being squeezed to width alone. A monospace family has
+to stay monospace: a code listing lines its columns up on one fixed
+advance, and a proportional face fitted to whole fragments put gaps after
+every syntax-coloured run. Any other installed family is stepped over, and
+the character lands on the shipped face the document's own font stack
+names next — what the browser does when a font has no glyph, which is why
+`OfficeFonts.stack()` is on the end of every font-family the editor writes.
+
+Because a stand-in is not the face the line was measured in, the *ink* of
+each fragment is then fitted to the place and width the browser gave it
+(`planRun` measures the fragment without the spaces at its ends, which a
+stand-in sets at another width; `Tz` does the squeeze), so it cannot push
+the rest of the line out of shape; when the face *is* the one the browser
+used, the ratio is 1 and nothing happens. Spaces in a highlighted span are
+still drawn as their highlight box.
 
 Two things about placing the text that are easy to get wrong, and were:
 

+ 34 - 7
src/web/Office/common/fonts.js

@@ -437,7 +437,7 @@ var OfficeFonts = (function () {
     }
     function kindOf(key) {
         if (METRICS[key]) return METRICS[key][0];
-        if (/mono|courier|consol|code|typewriter|terminal/.test(key)) return "mono";
+        if (/mono|courier|consol|code|typewriter|terminal|monaco/.test(key)) return "mono";
         if (/serif/.test(key) && !/sans/.test(key)) return "serif";
         if (/times|roman|garamond|georgia|antiqua|palatino|cambria|baskerville|bodoni|didot|caslon|schoolbook|bookman|constantia|rockwell|slab|playfair|merriweather|lora|minion|charter|cochin|perpetua|centaur|goudy|elephant|bell mt|calisto|californian|cooper|footlight|high tower|modern no|niagara|poor richard|book/.test(key)) return "serif";
         return "sans";
@@ -564,7 +564,8 @@ var OfficeFonts = (function () {
                 // gets a face of its own - itself, at its own size - so its
                 // ascent and descent can be restated (see below)
                 if (lines === "powerpoint" && METRICS[key]) {
-                    plans.push({ name: name, key: key, mk: key, heavy: false, via: name, self: true });
+                    plans.push({ name: name, key: key, mk: key, heavy: false, via: name, self: true,
+                        kind: kindOf(key) });
                 }
                 return;
             }
@@ -688,7 +689,7 @@ var OfficeFonts = (function () {
                     finalLoads.push(STYLE_DESC[s2].css + ' 16px "' + pl.name.replace(/["\\]/g, "") + '"');
                 }
                 substituted[pl.key] = { via: pl.via || "Noto Sans", adjust: adj, kind: pl.kind,
-                    twin: !!(pl.twin || pl.exact), heavy: !!pl.heavy };
+                    twin: !!(pl.twin || pl.exact), heavy: !!pl.heavy, self: !!pl.self };
             });
             probeEl.parentNode.removeChild(probeEl);
             if (!styleEl) {
@@ -724,14 +725,37 @@ var OfficeFonts = (function () {
 
     /* the stand-in a family was given, for exporters that draw text
        themselves: { via: "Arial", adjust: [r, b, i, bi], kind: "sans",
-       twin: false, heavy: false } or null. twin: via is a shipped metric
-       twin, which an exporter can embed in place of the original. heavy:
-       a weighted name ("Open Sans SemiBold") drawn from via's bold file in
-       every style, whatever weight the text asks for. */
+       twin: false, heavy: false, self: false } or null. twin: via is a
+       shipped metric twin, which an exporter can embed in place of the
+       original. heavy: a weighted name ("Open Sans SemiBold") drawn from
+       via's bold file in every style, whatever weight the text asks for.
+       self: the family is installed and via is the family itself - the face
+       only restates its line metrics, so the screen draws the real font. */
     function substituteOf(family) {
         return substituted[norm(family)] || null;
     }
 
+    // kindOf for a family name: "sans", "serif" or "mono"
+    function familyKind(family) {
+        var key = norm(family);
+        return kindOf(metricKey(key) || key);
+    }
+    // the shipped family drawn to a family's metrics, "" when there is none
+    function twinOf(family) {
+        var key = norm(family);
+        var t = TWINS[key] || TWINS[metricKey(key)];
+        return t ? SHIPPED[t].family : "";
+    }
+    /* widthOf is a family's average advance per em on SAMPLE in one style
+       (st: 0 regular, 1 bold, 2 italic, 3 bold italic), 0 when it was never
+       measured. The ratio of two is how much larger one face has to be
+       drawn to set text as wide as the other. */
+    function widthOf(family, st) {
+        var mk = metricKey(norm(family));
+        var w = mk ? METRICS[mk][1] : null;
+        return (w && w[st]) || 0;
+    }
+
     return {
         DIR: DIR,
         MENU: MENU,
@@ -742,6 +766,9 @@ var OfficeFonts = (function () {
         preload: preload,
         substitute: substitute,
         substituteOf: substituteOf,
+        kindOf: familyKind,
+        twinOf: twinOf,
+        widthOf: widthOf,
         familiesIn: familiesIn,
         // resolves once every substitution asked for so far is in place
         ready: function () { return pending; }

+ 194 - 73
src/web/Office/common/pdfcore.js

@@ -96,9 +96,11 @@ var OfficePdfCore = (function () {
        be measured: document.fonts.check() answers "is it loaded", and for a
        local family Chrome says yes whatever name you give it. The reliable
        test is the old one - render a probe string backed by two different
-       generics; a family that exists overrides both and comes out a
-       different width from each, one that does not falls through to the
-       generic and matches it exactly.
+       generics; a family that does not exist falls through to the generic
+       and matches both exactly, one that exists overrides them and comes
+       out a different width from at least one. Only one: a family can be
+       a generic's own default (Consolas is Chrome's monospace on Windows,
+       Times New Roman its serif), and then it matches that generic.
 
        This matters because a deck may ask for a font the machine does not
        have: the browser laid the text out in the fallback, so the fallback
@@ -118,10 +120,10 @@ var OfficePdfCore = (function () {
                     probeBase[g] = probeCtx.measureText(PROBE).width;
                 });
             }
-            var found = true;
+            var found = false;
             ["monospace", "serif"].forEach(function (g) {
                 probeCtx.font = '72px "' + name.replace(/"/g, "") + '", ' + g;
-                if (probeCtx.measureText(PROBE).width === probeBase[g]) found = false;
+                if (probeCtx.measureText(PROBE).width !== probeBase[g]) found = true;
             });
             familyKnown[name] = found;
         } catch (e) {
@@ -283,9 +285,11 @@ var OfficePdfCore = (function () {
        asks for: a weighted family name ("Open Sans SemiBold") that the
        screen draws from its base family's bold file (OfficeFonts.substitute).
 
-       A family that is neither - a system font - is stepped over rather
-       than used: its bytes are unreadable, so the character goes to the
-       next entry, which is the shipped face for its script. */
+       scale, when it is there, is how much larger than the run's size the
+       face has to be drawn (standIn).
+
+       A family that is neither - a system font - cannot be embedded, its
+       bytes are unreadable; standIn says what is drawn in its place. */
     function resolveChar(cp, names, fonts, bold, italic) {
         for (var i = 0; i < names.length; i++) {
             var name = names[i];
@@ -303,31 +307,109 @@ var OfficePdfCore = (function () {
             if (STD_FAMILIES[key] && (GENERICS[key] || haveFamily(name)) && winAnsiCp(cp)) {
                 return { std: STD_FAMILIES[key] };
             }
-            // a family this machine lacks was drawn in a stand-in of the
-            // same kind (OfficeFonts.substitute): the standard font of that
-            // kind is far nearer to it than the shipped sans further down
-            // the stack, and the fragment is fitted to the browser's width
-            var sub = OfficeFonts.substituteOf ? OfficeFonts.substituteOf(name) : null;
-            // a metric twin the suite ships stood in on screen: the PDF
-            // embeds that same face
-            var sb = !!(sub && sub.heavy);
-            if (sub && sub.twin) {
-                var tw = fonts.shipped(sub.via, bold || sb, italic);
-                if (!tw) {
-                    if (!fonts.tried(sub.via, bold || sb, italic)) return { need: sub.via, bold: sb };
-                } else if (!(tw.kit && tw.kit.hasGlyphForCodePoint && !tw.kit.hasGlyphForCodePoint(cp))) {
-                    return { shipped: sub.via, bold: sb };
+            var res = standIn(cp, name, fonts, bold, italic);
+            if (res) return res;
+        }
+        return null;
+    }
+
+    /* standIn answers for a system font, which the PDF cannot carry. What
+       the screen drew it in decides, tried in this order:
+
+         - a family this machine lacks was drawn in a stand-in of its own
+           (OfficeFonts.substitute): a shipped metric twin is embedded as
+           it is, a shipped face is that same face, an installed one is the
+           standard font or shipped twin that matches it
+         - an installed family is drawn in itself, and the nearest face of
+           its kind takes its place: its metric twin when the suite ships
+           one (Calibri -> Carlito), else Cousine for a monospace family and
+           the standard font of its kind for the rest
+
+       A monospace family needs a monospace face whatever the stack says
+       next. The browser set every character of it on one fixed advance, a
+       code listing lines its columns up on that, and a proportional face
+       fitted to a whole fragment cannot put a single character back where
+       it was - the gaps and drifting columns that used to come out of
+       every syntax-coloured listing. So an installed monospace family the
+       substitution never looked at (Docs only gives a face to a family
+       the machine lacks) stands in too, and so does one with a shipped
+       metric twin; any other is stepped over and the next family in the
+       stack (the shipped face for the script) gets the character, as the
+       browser would.
+
+       The face is drawn at the size that gives it the original's advance
+       (scale, from both families' measured widths): Cousine set at 0.917
+       of the size is Consolas's width and nearly its x-height, which a
+       squeeze to width alone (Tz) would leave 9% too tall. The fragment
+       is still fitted to the browser's width after that. */
+    var MONO_STAND_IN = "Cousine";
+    // the measured families the standard fonts are metric-identical to
+    var STD_METRIC = { Helvetica: "Arial", TimesRoman: "Times New Roman", Courier: "Courier New" };
+    function standIn(cp, name, fonts, bold, italic) {
+        var key = name.toLowerCase();
+        var sub = OfficeFonts.substituteOf ? OfficeFonts.substituteOf(name) : null;
+        if (!sub && (GENERICS[key] || (OfficeFonts.kindOf(name) !== "mono" && !OfficeFonts.twinOf(name)) ||
+            !haveFamily(name))) return null;
+        var sb = !!(sub && sub.heavy);
+        var b = bold || sb;
+        // the face the screen really drew the family in
+        var base = sub && !sub.self ? sub.via : name;
+        var kind = (sub && sub.kind) || OfficeFonts.kindOf(base);
+        var tries = [];
+        if (sub && sub.twin) {
+            tries.push({ shipped: sub.via });
+        } else {
+            if (OfficeFonts.isShipped(base)) tries.push({ shipped: base });
+            var std = STD_FAMILIES[String(base).toLowerCase()];
+            if (std) tries.push({ std: std });
+            var twin = OfficeFonts.twinOf(base);
+            if (twin) tries.push({ shipped: twin });
+            if (kind === "mono") tries.push({ shipped: MONO_STAND_IN });
+        }
+        tries.push({ std: { serif: "TimesRoman", mono: "Courier" }[kind] || "Helvetica" });
+        for (var i = 0; i < tries.length; i++) {
+            var t = tries[i];
+            if (t.shipped) {
+                var rec = fonts.shipped(t.shipped, b, italic);
+                if (!rec) {
+                    if (!fonts.tried(t.shipped, b, italic)) return { need: t.shipped, bold: sb };
+                    continue;
                 }
+                if (rec.kit && rec.kit.hasGlyphForCodePoint && !rec.kit.hasGlyphForCodePoint(cp)) continue;
+                return scaled({ shipped: t.shipped, bold: sb }, name, sub, t.shipped, b, italic);
             }
-            if (sub && winAnsiCp(cp)) {
-                var std = STD_FAMILIES[String(sub.via).toLowerCase()] ||
-                    { serif: "TimesRoman", mono: "Courier" }[sub.kind] || "Helvetica";
-                return { std: std, bold: sb };
-            }
+            if (winAnsiCp(cp)) return scaled({ std: t.std, bold: sb }, name, sub, STD_METRIC[t.std], b, italic);
         }
         return null;
     }
 
+    // scaled adds the size a stand-in is drawn at to a resolved answer:
+    // the width the browser set the family at over the stand-in's own
+    var scaleCache = {};
+    function scaled(res, name, sub, face, bold, italic) {
+        var st = (bold ? 1 : 0) + (italic ? 2 : 0);
+        var ck = name + "|" + face + "|" + st;
+        if (scaleCache[ck] === undefined) {
+            var k = 1;
+            if (face) {
+                var ratio = function (s) {
+                    // the original's measurement; a family that was never
+                    // measured was set at its stand-in's width, size-adjusted
+                    var want = OfficeFonts.widthOf(name, s) || (sub && !sub.self ?
+                        OfficeFonts.widthOf(sub.via, s) * ((sub.adjust && sub.adjust[s]) || 1) : 0);
+                    var got = OfficeFonts.widthOf(face, s);
+                    return want > 0 && got > 0 ? want / got : 0;
+                };
+                // a style one side never measured: the regulars' ratio
+                k = clamp(ratio(st) || ratio(0) || 1, 0.6, 1.6);
+                if (Math.abs(k - 1) < 0.002) k = 1;
+            }
+            scaleCache[ck] = Math.round(k * 10000) / 10000;
+        }
+        if (scaleCache[ck] !== 1) res.scale = scaleCache[ck];
+        return res;
+    }
+
     /* segmentText cuts a fragment into the pieces that share one font, the
        way a browser does per character. Returns null when any character has
        nowhere to go, which is the signal to rasterize instead; an empty list
@@ -341,24 +423,27 @@ var OfficePdfCore = (function () {
             if (ignorableCp(cp)) continue;
             var res = resolveChar(cp, names, fonts, bold, italic);
             if (!res || res.need) return null;
-            var key = (res.std ? "s:" + res.std : "f:" + res.shipped) + (res.bold ? ":b" : "");
+            var key = (res.std ? "s:" + res.std : "f:" + res.shipped) + (res.bold ? ":b" : "") +
+                (res.scale ? ":" + res.scale : "");
             if (cur && cur.key === key) cur.text += ch;
             else { cur = { key: key, res: res, text: ch }; segs.push(cur); }
         }
         return segs;
     }
 
-    // faceOf: the font a resolved piece is drawn in, and what of its style
-    // has to be synthesized (family is the name the page declared it under)
+    // faceOf: the font a resolved piece is drawn in, what of its style has
+    // to be synthesized (family is the name the page declared it under) and
+    // the multiple of the run's size it is drawn at
     function faceOf(res, fonts, bold, italic) {
         bold = bold || !!res.bold;
-        if (res.std) return { font: fonts.std(res.std, bold, italic), synthBold: false, synthItalic: false };
+        var scale = res.scale || 1;
+        if (res.std) return { font: fonts.std(res.std, bold, italic), synthBold: false, synthItalic: false, scale: scale };
         var rec = fonts.shipped(res.shipped, bold, italic);
         if (!rec) return null;
         var face = OfficeFonts.faceFor(res.shipped, bold, italic);
         return {
             font: rec.font, synthBold: rec.synthBold, synthItalic: rec.synthItalic,
-            family: face ? face.family : res.shipped
+            family: face ? face.family : res.shipped, scale: scale
         };
     }
 
@@ -555,16 +640,25 @@ var OfficePdfCore = (function () {
 
     /* eachTextNode is the walk both the font pre-pass and the run collector
        make, kept in one place so they cannot disagree about what counts as
-       text on the slide. */
-    function eachTextNode(rootEl, fn) {
+       text on the slide.
+
+       painted: also hand over text that is only spaces when it sits in an
+       inline element with a background - a highlight shows as a box over
+       the spaces too (the indent of a highlighted code listing). Only the
+       run collector asks for it: there is no character in it to find a
+       font for. */
+    function eachTextNode(rootEl, fn, painted) {
         var walker = document.createTreeWalker(rootEl, NodeFilter.SHOW_TEXT, null);
         var node;
         while ((node = walker.nextNode())) {
             var text = node.nodeValue;
-            if (!text || !visibleText(text).trim()) continue;
+            if (!text) continue;
             var parent = node.parentElement;
             if (!parent) continue;
+            var blank = !visibleText(text).trim();
+            if (blank && !painted) continue;
             var cs = window.getComputedStyle(parent);
+            if (blank && (cs.display !== "inline" || !parseFill(cs.backgroundColor))) continue;
             if (cs.visibility === "hidden" || cs.display === "none") continue;
             // source newlines and tabs are whitespace the browser already
             // collapsed; they must not reach a font, but the string has to
@@ -697,6 +791,8 @@ var OfficePdfCore = (function () {
             var range = document.createRange();
             range.selectNodeContents(node);
             var rects = Array.prototype.slice.call(range.getClientRects());
+            // spaces the browser collapsed away paint no highlight either
+            if (!visibleText(text).trim()) rects = rects.filter(function (rc) { return rc.width > 0.01; });
             if (!rects.length) return;
             var ls = parseFloat(cs.letterSpacing);
             var shared = {
@@ -722,7 +818,7 @@ var OfficePdfCore = (function () {
                 r.start = ln.start;
                 runs.push(r);
             });
-        });
+        }, true);
         return runs;
     }
 
@@ -779,38 +875,54 @@ var OfficePdfCore = (function () {
        back with its place in the line, measured off the DOM, so a picture
        in the middle of a sentence lands between the words around it:
            [{ text, dx, w, fit, raster }]
-       dx is from the run's left edge; fit is the width to fit text to, 0
-       when the piece begins or ends on a space (the browser collapses
-       those, the measurement does not). */
+       dx is from the run's left edge; fit is the width to fit text to.
+
+       Spaces at either end of a piece are left out of it. They draw
+       nothing, and the width the browser gave them is not the one a
+       stand-in face gives them (Consolas sets a space at 0.55 em,
+       Helvetica at 0.28) - so a fragment fitted with them would put its
+       ink in the wrong place, and one left unfitted because of them
+       ("x := " in a code listing) drifted off its neighbours. The piece is
+       the ink alone, at the place and width the browser gave the ink. */
+    var EDGE_SPACE = /^\s|\s$/;
     function planRun(r, fonts) {
         var bold = r.weight >= 600;
         var whole = r.rect.right - r.rect.left;
+        // where the ink starts and ends in the run: nothing to draw without it
+        var inkStart = r.text.search(/\S/);
+        if (inkStart < 0) return [];
+        var inkEnd = r.text.replace(/\s+$/, "").length;
         var shown = transformText(r.text, r.transform);
+        var parts;
         if (segmentText(shown, r.names, fonts, bold, r.italic)) {
-            return [{ text: shown, dx: 0, w: whole, fit: /^\s|\s$/.test(r.text) ? 0 : whole, raster: false }];
-        }
-        // cut where drawability changes; a character that draws nothing
-        // (a joiner inside an emoji) stays with what is around it
-        var parts = [], cur = null;
-        for (var i = 0; i < r.text.length;) {
-            var cp = r.text.codePointAt(i), n = cp > 0xFFFF ? 2 : 1;
-            var ok;
-            if (ignorableCp(cp)) {
-                ok = cur ? cur.ok : true;
-            } else {
-                var shownCp = transformText(String.fromCodePoint(cp), r.transform).codePointAt(0);
-                var res = resolveChar(shownCp, r.names, fonts, bold, r.italic);
-                ok = !!(res && !res.need);
+            if (!EDGE_SPACE.test(r.text)) return [{ text: shown, dx: 0, w: whole, fit: whole, raster: false }];
+            parts = [{ ok: true, start: inkStart, end: inkEnd }];
+        } else {
+            // cut where drawability changes; a character that draws nothing
+            // (a joiner inside an emoji) stays with what is around it
+            var cur = null;
+            parts = [];
+            for (var i = 0; i < r.text.length;) {
+                var cp = r.text.codePointAt(i), n = cp > 0xFFFF ? 2 : 1;
+                var ok;
+                if (ignorableCp(cp)) {
+                    ok = cur ? cur.ok : true;
+                } else {
+                    var shownCp = transformText(String.fromCodePoint(cp), r.transform).codePointAt(0);
+                    var res = resolveChar(shownCp, r.names, fonts, bold, r.italic);
+                    ok = !!(res && !res.need);
+                }
+                if (cur && cur.ok === ok) cur.end = i + n;
+                else { cur = { ok: ok, start: i, end: i + n }; parts.push(cur); }
+                i += n;
             }
-            if (cur && cur.ok === ok) cur.end = i + n;
-            else { cur = { ok: ok, start: i, end: i + n }; parts.push(cur); }
-            i += n;
         }
         /* Each piece is measured against the whole line at the same moment,
            so the place comes out right even when the page is no longer at
            the zoom it was collected at (Docs hands the page back before it
            writes its display list). A line whose text node has changed
-           since cannot be measured: it goes in whole, as a picture. */
+           since cannot be measured: it goes in whole - as text, unfitted,
+           when a font can show all of it, else as a picture. */
         var range = document.createRange();
         var now = null;
         try {
@@ -818,22 +930,29 @@ var OfficePdfCore = (function () {
             range.setEnd(r.node, r.start + r.text.length);
             now = range.getBoundingClientRect();
         } catch (e) { now = null; }
-        if (!now || !(now.width > 0) || r.node.nodeValue.substr(r.start, r.text.length) !== r.text) {
-            return [{ text: shown, dx: 0, w: whole, fit: 0, raster: true }];
+        var nodeText = String(r.node.nodeValue || "").substr(r.start, r.text.length)
+            .replace(/[\u0000-\u001F\u007F]/g, " ");
+        if (!now || !(now.width > 0) || nodeText !== r.text) {
+            var drawable = parts.length === 1 && parts[0].ok;
+            return [{ text: shown, dx: 0, w: whole, fit: 0, raster: !drawable }];
         }
         var k = whole / now.width;
         var out = [];
         parts.forEach(function (p) {
-            var text = r.text.substring(p.start, p.end);
-            range.setStart(r.node, r.start + p.start);
-            range.setEnd(r.node, r.start + p.end);
+            var s = p.start, e = p.end;
+            if (p.ok) {
+                // a text piece is its ink alone (see above)
+                while (s < e && /\s/.test(r.text[s])) s++;
+                while (e > s && /\s/.test(r.text[e - 1])) e--;
+                if (s === e) return;
+            }
+            var text = r.text.substring(s, e);
+            range.setStart(r.node, r.start + s);
+            range.setEnd(r.node, r.start + e);
             var b = range.getBoundingClientRect();
             var dx = (b.left - now.left) * k, w = b.width * k;
             if (!(w > 0) && !visibleText(text).trim()) return;
-            out.push({
-                text: transformText(text, r.transform), dx: dx, w: w,
-                fit: /^\s|\s$/.test(text) ? 0 : w, raster: !p.ok
-            });
+            out.push({ text: transformText(text, r.transform), dx: dx, w: w, fit: w, raster: !p.ok });
         });
         return out;
     }
@@ -872,6 +991,8 @@ var OfficePdfCore = (function () {
        costs nothing when the PDF font is the one the browser used (the
        ratio is 1) and is what keeps a substituted face - a system font we
        could not embed - from pushing the rest of the line out of place.
+       Such a face is first drawn at its own multiple of the size (standIn),
+       so what is left for Tz is the difference between two designs.
 
        Bold that a shipped face does not have is stroked rather than filled,
        and italic it does not have is slanted, both by as much as the
@@ -891,11 +1012,12 @@ var OfficePdfCore = (function () {
             var face = faceOf(segs[i].res, fonts, spec.bold, spec.italic);
             if (!face) return 0;
             segs[i].face = face;
-            segs[i].w = face.font.widthOfTextAtSize(segs[i].text, spec.sizePx) +
+            segs[i].size = spec.sizePx * face.scale;
+            segs[i].w = face.font.widthOfTextAtSize(segs[i].text, segs[i].size) +
                 (ls ? ls * Array.from(segs[i].text).length : 0);
             if (face.synthBold || face.synthItalic) {
                 segs[i].synth = synthStyle(face.family, spec.weight || (spec.bold ? 700 : 400), spec.italic,
-                    spec.sizePx, segs[i].text, face.synthBold, face.synthItalic);
+                    segs[i].size, segs[i].text, face.synthBold, face.synthItalic);
             }
             total += segs[i].w;
         }
@@ -924,7 +1046,7 @@ var OfficePdfCore = (function () {
             if (ops.length) pg.ops(ops);
             var opt = {
                 x: px(cursor), y: pg.y(spec.baselinePx),
-                size: px(spec.sizePx), font: seg.face.font, color: col
+                size: px(seg.size), font: seg.face.font, color: col
             };
             // the text matrix's horizontal shear by height (pdf-lib calls
             // that angle ySkew)
@@ -952,24 +1074,23 @@ var OfficePdfCore = (function () {
             var col = parseColor(r.color) || PDFLib.rgb(0, 0, 0);
             var bg = parseFill(r.background);
             if (bg) pg.rect(x, top, domW, lineH, { fill: bg.c, fillOpacity: bg.a });
-            var drawn = 0;
             planRun(r, pg.fonts).forEach(function (pc) {
                 if (pc.raster) {
                     var pic = drawImage ? rasterText(r, pc.text, pc.w, lineH, baseline) : null;
                     if (pic) drawImage(pic.src, x + pc.dx + pic.x, top + pic.y, pic.w, pic.h);
-                    drawn += pc.w;
                     return;
                 }
-                drawn += drawFragment(pg, {
+                drawFragment(pg, {
                     text: pc.text, names: r.names,
                     bold: r.weight >= 600, weight: r.weight, italic: r.italic,
                     sizePx: r.size, xPx: x + pc.dx, baselinePx: top + baseline,
                     color: col, fitPx: pc.fit, letterSpacing: r.letterSpacing
                 });
             });
+            // the browser decorates the whole fragment, spaces included
             if (r.underline || r.strike) {
                 var yOff = r.underline ? baseline + r.size * 0.11 : baseline - r.size * 0.28;
-                pg.rect(x, top + yOff, drawn || domW, Math.max(0.7, r.size * 0.06), { fill: col });
+                pg.rect(x, top + yOff, domW, Math.max(0.7, r.size * 0.06), { fill: col });
             }
         });
     }

+ 9 - 6
src/web/Office/common/pdfdraw.js

@@ -24,10 +24,11 @@
         ["rect", x, y, w, h, rgb, alpha]
         ["image", id, x, y, w, h, crop]       crop {t,r,b,l} fractions | null
         ["text", x, baseline, size, rgb, fitW, segs, deco, letterSpacing]
-              segs [[text, font, bold, skew]]  font "s:Helvetica:bold:italic" | "f:<url>"
+              segs [[text, font, bold, skew, k]]  font "s:Helvetica:bold:italic" | "f:<url>"
                    bold: synthetic bold stroke width in px (0: none), skew:
                    synthetic italic shear (0: upright) - both as measured
-                   in the page (OfficePdfCore.synthStyle)
+                   in the page (OfficePdfCore.synthStyle); k: the size
+                   multiple a stand-in face is drawn at (default 1)
               deco [y, h, w] underline/strike bar, w used when nothing drew
               letterSpacing px after every character, optional
         ["leader", x, w, baseline, size, rgb, ch, font]
@@ -273,10 +274,12 @@ var OfficePdfDraw = (function () {
                 var s = op[6][i];
                 var font = fontReady[s[1]];
                 if (!font) return;
-                var w = font.widthOfTextAtSize(s[0], size) + (ls ? ls * Array.from(s[0]).length : 0);
+                // s[4]: a stand-in face is drawn at its own multiple of the size
+                var sz = size * (s[4] || 1);
+                var w = font.widthOfTextAtSize(s[0], sz) + (ls ? ls * Array.from(s[0]).length : 0);
                 // s[2]: the synthetic bold stroke in px (true: the old fixed one)
-                var bw = typeof s[2] === "number" ? s[2] : (s[2] ? size / 28 : 0);
-                segs.push({ text: s[0], font: font, bold: bw, skew: s[3] || 0, w: w });
+                var bw = typeof s[2] === "number" ? s[2] : (s[2] ? sz / 28 : 0);
+                segs.push({ text: s[0], font: font, bold: bw, skew: s[3] || 0, w: w, size: sz });
                 total += w;
             }
             var scale = 1;
@@ -297,7 +300,7 @@ var OfficePdfDraw = (function () {
                     ops.push(PDFLib.setStrokingColor(col));
                 }
                 push(ops);
-                var opt = { x: cursor * PX, y: y(baseline), size: size * PX, font: seg.font, color: col };
+                var opt = { x: cursor * PX, y: y(baseline), size: seg.size * PX, font: seg.font, color: col };
                 // a synthetic italic: the text matrix's shear by height
                 if (seg.skew > 0.001) opt.ySkew = PDFLib.radians(Math.atan(seg.skew));
                 page.drawText(seg.text, opt);

+ 11 - 8
src/web/Office/docs/docs_pdf.js

@@ -193,8 +193,9 @@ var DocsPdf = (function () {
 
         // text, as line fragments at their baselines
         var origin = { left: frame.left, top: frame.top, x: 0, y: 0 };
+        // spaces stay only for the highlight they carry
         var runs = C.collectRuns(o.pageEl, origin).filter(function (run) {
-            return C.visibleText(run.text).trim() !== "";
+            return C.visibleText(run.text).trim() !== "" || !!C.parseFill(run.background);
         });
         runs.forEach(function (run) {
             var top = run.rect.top - frame.top;
@@ -320,10 +321,11 @@ var DocsPdf = (function () {
     }
 
     /* the pieces a line fragment is spelled in, as display-list fonts:
-       [text, font, synthetic bold stroke px, synthetic italic shear]. null
-       when a character has no font, an empty list when nothing in it draws
-       anything. st is { weight, size }: how much the browser emboldens or
-       slants a face depends on both, and is measured (synthStyle). */
+       [text, font, synthetic bold stroke px, synthetic italic shear, size
+       multiple]. null when a character has no font, an empty list when
+       nothing in it draws anything. st is { weight, size }: how much the
+       browser emboldens or slants a face depends on both, and is measured
+       (synthStyle). The size multiple is a stand-in's (C.resolveChar). */
     function segsFor(text, names, fonts, bold, italic, st) {
         var segs = C.segmentText(text, names, fonts, bold, italic);
         if (!segs) return null;
@@ -331,14 +333,15 @@ var DocsPdf = (function () {
         for (var i = 0; i < segs.length; i++) {
             var res = segs[i].res;
             var b = bold || !!res.bold;
+            var k = res.scale || 1;
             if (res.std) {
-                out.push([segs[i].text, "s:" + res.std + ":" + (b ? 1 : 0) + ":" + (italic ? 1 : 0), 0, 0]);
+                out.push([segs[i].text, "s:" + res.std + ":" + (b ? 1 : 0) + ":" + (italic ? 1 : 0), 0, 0, k]);
             } else {
                 var face = OfficeFonts.faceFor(res.shipped, b, italic);
                 if (!face) return null;
                 var syn = (face.synthBold || face.synthItalic) ?
-                    C.synthStyle(face.family, st.weight, italic, st.size, segs[i].text, face.synthBold, face.synthItalic) : null;
-                out.push([segs[i].text, "f:" + absUrl(face.url), syn ? syn.bold : 0, syn ? syn.skew : 0]);
+                    C.synthStyle(face.family, st.weight, italic, st.size * k, segs[i].text, face.synthBold, face.synthItalic) : null;
+                out.push([segs[i].text, "f:" + absUrl(face.url), syn ? syn.bold : 0, syn ? syn.skew : 0, k]);
             }
         }
         return out;

+ 11 - 6
src/web/Office/slides/slides_pdf.js

@@ -50,11 +50,16 @@
          do those characters come in as a picture of themselves, drawn by
          the page's own canvas in the page's own fonts.
 
-    A system font that is none of the above is substituted by the shipped
-    face the document's own font stack names next, which is the same thing
-    the browser does when it has no glyph. The fragment is then squeezed to
-    the width the browser gave it (Tz), so a substituted face cannot push a
-    line out of shape.
+    A system font that is none of the above stands in as the nearest face
+    of its kind (OfficePdfCore.resolveChar): its shipped metric twin, the
+    standard font of its kind, Cousine for any monospace family - drawn at
+    the size that gives it the original's advance. Any other installed
+    family the editor never measured is substituted by the shipped face the
+    document's own font stack names next, which is what the browser does
+    when it has no glyph.
+    The ink of each fragment is then fitted to the place and width the
+    browser gave it (Tz), so a substituted face cannot push a line out of
+    shape.
 
     Where it runs. Each slide is measured and drawn in the page, but onto a
     recording (OfficePdfDraw.recorder, common/pdfdraw.js): every pdf-lib
@@ -423,7 +428,7 @@ var SlidesPdf = (function () {
                         var twPx = 0;
                         segs.forEach(function (seg) {
                             var f = faceOf(seg.res, pg.fonts, bold, false);
-                            if (f) twPx += f.font.widthOfTextAtSize(seg.text, sizePx);
+                            if (f) twPx += f.font.widthOfTextAtSize(seg.text, sizePx * f.scale);
                         });
                         var anchor = c.getAttribute("text-anchor") || "start";
                         var tx = X(parseFloat(c.getAttribute("x") || 0));