feat: add embedded font loading

This commit is contained in:
Steffen Becker committed 2026-07-11 14:07:36 +02:00
1 parent b8233e894e
commit 40c139dd2c
8 files changed
+212 -4

No files matched your search

+31
View File
@@ -13,6 +13,7 @@ import { formatFromCm, type PageFormat } from '../storage/pageFormat';
import { languageFromOdf, NO_LANGUAGE, type DocumentLanguage } from '../storage/documentLanguage';
import type { HfDoc } from '../storage/headerFooter';
import type { OdtImportResult } from './odt';
import { deobfuscateOdttf, type EmbeddedFont } from '../fonts/embeddedFonts';
// .docx → TipTap JSON, inverting export/docx.ts. Editor-expressible OOXML becomes its
// native node/mark/attr; values matching the editor's defaults are suppressed so round
@@ -139,10 +140,40 @@ export function importDocx(bytes: Uint8Array, convertedImages: ConvertedImages =
headerDistanceCm: sect.header ? sect.headerDistCm : null,
footerDistanceCm: sect.footer ? sect.footerDistCm : null,
language: documentLanguage(stylesDoc, warnings),
fonts: extractDocxFonts(files),
warnings: [...warnings],
};
}
// Fonts embedded via word/fontTable.xml: each <w:font> may reference regular/bold/italic/
// bold-italic .odttf binaries (obfuscated). Resolve r:id → package path, read + de-obfuscate.
function extractDocxFonts(files: Record<string, Uint8Array>): EmbeddedFont[] {
const ftBytes = files['word/fontTable.xml'];
if (!ftBytes) return [];
let doc: Document;
try { doc = parseXml(strFromU8(ftBytes)); } catch { return []; }
const rels = parseRels(files['word/_rels/fontTable.xml.rels']);
const embeds: [string, 'normal' | 'bold', 'normal' | 'italic'][] = [
['embedRegular', 'normal', 'normal'], ['embedBold', 'bold', 'normal'],
['embedItalic', 'normal', 'italic'], ['embedBoldItalic', 'bold', 'italic'],
];
const out: EmbeddedFont[] = [];
for (const font of Array.from(doc.getElementsByTagNameNS(W, 'font'))) {
const family = font.getAttributeNS(W, 'name');
if (!family) continue;
for (const [tag, weight, style] of embeds) {
const el = fc(font, tag);
const rel = el ? rels.get(el.getAttributeNS(R, 'id') ?? '') : undefined;
if (!el || !rel || rel.external) continue;
const data = files['word/' + rel.target.replace(/^\/+/, '')];
if (!data) continue;
const key = el.getAttributeNS(W, 'fontKey');
out.push({ family, weight, style, data: key ? deobfuscateOdttf(data, key) : data });
}
}
return out;
}
function parseRels(bytes: Uint8Array | undefined): Map<string, RelInfo> {
const map = new Map<string, RelInfo>();
if (!bytes) return map;
+10
View File
@@ -11,6 +11,7 @@ import type { Orientation } from '../storage/pageOrientation';
import type { PageFormat } from '../storage/pageFormat';
import { languageFromOdf, NO_LANGUAGE, type DocumentLanguage } from '../storage/documentLanguage';
import type { HfDoc } from '../storage/headerFooter';
import type { EmbeddedFont } from '../fonts/embeddedFonts';
// .odt → TipTap JSON, inverting export/odt.ts. Editor-expressible content becomes its
// native node/mark/attr; values matching the editor's defaults are suppressed so round
@@ -39,6 +40,8 @@ export interface OdtImportResult {
// Document spell-check language; NO_LANGUAGE when the file's language has no
// bundled dictionary; null when the file declares none.
language: DocumentLanguage | null;
// Fonts embedded in the package, to register via FontFace so they render.
fonts: EmbeddedFont[];
warnings: string[];
}
@@ -343,6 +346,12 @@ export function importOdt(bytes: Uint8Array, convertedImages: ConvertedImages =
const geometry = resolver.pageGeometry();
const edge = resolver.edgeDistancesCm();
const fonts: EmbeddedFont[] = [];
for (const s of resolver.embeddedFontSources()) {
const data = files[s.href];
if (data) fonts.push({ family: s.family, weight: s.weight, style: s.style, data });
}
const odfLang = resolver.documentLanguage();
let language: DocumentLanguage | null = null;
if (odfLang) {
@@ -366,6 +375,7 @@ export function importOdt(bytes: Uint8Array, convertedImages: ConvertedImages =
headerDistanceCm: hf.header ? edge?.top ?? null : null,
footerDistanceCm: hf.footer ? edge?.bottom ?? null : null,
language,
fonts,
warnings: [...warnings],
};
}
+27 -4
View File
@@ -16,8 +16,18 @@ export const NS = {
draw: 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
xlink: 'http://www.w3.org/1999/xlink',
number: 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
loext: 'urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0',
} as const;
// One embedded-font binary referenced from a <style:font-face>: the CSS family runs use,
// the package href of the font file, and the face's weight/style.
export interface EmbeddedFontSource {
family: string;
href: string;
weight: 'normal' | 'bold';
style: 'normal' | 'italic';
}
// Property keys are stored as "alias:localName" for the namespaces we care
// about; attributes from other namespaces are dropped.
const ALIAS_BY_URI = new Map<string, string>(Object.entries(NS).map(([alias, uri]) => [uri, alias]));
@@ -102,6 +112,7 @@ export class StyleResolver {
private styles = new Map<string, StyleEntry>();
private defaults = new Map<string, StyleEntry>(); // family → style:default-style
private fontFaces = new Map<string, string>(); // style:name → first font-family
private fontSources: EmbeddedFontSource[] = []; // embedded font binaries
private listStyles = new Map<string, Element>(); // style:name → text:list-style
private numberStyles = new Map<string, Element>(); // style:name → number:date/time-style
// Section styles kept as raw elements: <style:columns> is a child element of
@@ -131,15 +142,27 @@ export class StyleResolver {
for (const el of Array.from(container.children)) {
if (el.namespaceURI !== NS.style || el.localName !== 'font-face') continue;
const name = el.getAttributeNS(NS.style, 'name');
if (!name) continue;
// svg:font-family may be a quoted list: 'Liberation Serif', 'Times New Roman'
const family = el.getAttributeNS(NS.svg, 'font-family');
if (name && family) {
// svg:font-family may be a quoted list: 'Liberation Serif', 'Times New Roman'
const first = family.split(',')[0].trim().replace(/^['"]|['"]$/g, '');
if (first) this.fontFaces.set(name, first);
const first = family ? family.split(',')[0].trim().replace(/^['"]|['"]$/g, '') : '';
if (first) this.fontFaces.set(name, first);
const cssFamily = first || name;
for (const uri of Array.from(el.getElementsByTagNameNS(NS.svg, 'font-face-uri'))) {
const href = uri.getAttributeNS(NS.xlink, 'href');
if (!href) continue;
const weight = uri.getAttributeNS(NS.loext, 'font-weight') === 'bold' ? 'bold' : 'normal';
const style = uri.getAttributeNS(NS.loext, 'font-style') === 'italic' ? 'italic' : 'normal';
this.fontSources.push({ family: cssFamily, href, weight, style });
}
}
}
// Embedded font binaries (one per <svg:font-face-uri>); importOdt maps href → bytes.
embeddedFontSources(): readonly EmbeddedFontSource[] {
return this.fontSources;
}
private scanContainer(container: Element): void {
for (const el of Array.from(container.children)) {
if (el.namespaceURI === NS.style && el.localName === 'style') {