@hilvana/office 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +9 -2
- package/dist/convert.d.ts +13 -0
- package/dist/convert.js +35 -0
- package/dist/fonts.d.ts +45 -0
- package/dist/fonts.js +146 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/layout.d.ts +43 -0
- package/dist/layout.js +525 -0
- package/dist/libreoffice.d.ts +11 -0
- package/dist/libreoffice.js +63 -0
- package/dist/model.d.ts +129 -0
- package/dist/model.js +3 -0
- package/dist/parse.d.ts +21 -0
- package/dist/parse.js +929 -0
- package/dist/word.d.ts +20 -0
- package/dist/word.js +22 -0
- package/package.json +56 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 gethilvana
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hilvana/office
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Word (`.docx`) → PDF **locally**, with real, selectable text. Own layout engine (styles, lists, tables, images, headers/footers with page numbers) with embedded open fonts metric-compatible with Office, plus an optional local LibreOffice engine for complex layouts.
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
import { wordToPdf } from '@hilvana/office';
|
|
7
|
+
const { pdf, pageCount, warnings } = await wordToPdf(docxBytes);
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Coverage and limits: [docs/word.md](https://github.com/gethilvana/hilvana/blob/main/docs/word.md) · MIT (fonts: SIL OFL 1.1)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type WordToPdfOptions, type WordToPdfResult } from './word.js';
|
|
2
|
+
export type WordEngine = 'auto' | 'native' | 'libreoffice';
|
|
3
|
+
/**
|
|
4
|
+
* Word → PDF with engine selection, for Node surfaces (CLI, MCP):
|
|
5
|
+
* - native: built-in engine, fast and dependency-free.
|
|
6
|
+
* - libreoffice: a local LibreOffice install, for maximum fidelity.
|
|
7
|
+
* - auto: native, unless it had to drop content and LibreOffice is installed.
|
|
8
|
+
* Both engines run on this machine; nothing is uploaded.
|
|
9
|
+
*/
|
|
10
|
+
export declare function convertWord(docx: Uint8Array, opts?: WordToPdfOptions & {
|
|
11
|
+
engine?: WordEngine;
|
|
12
|
+
}): Promise<WordToPdfResult>;
|
|
13
|
+
//# sourceMappingURL=convert.d.ts.map
|
package/dist/convert.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { PDFDocument } from 'pdf-lib';
|
|
2
|
+
import { wordToPdf } from './word.js';
|
|
3
|
+
/** Warnings that mean the native engine left content out (not just approximated it). */
|
|
4
|
+
const CONTENT_LOSS = ['TEXTBOX_SKIPPED', 'LEGACY_SHAPE_SKIPPED', 'NOTES_SKIPPED', 'UNSUPPORTED_IMAGE_FORMAT', 'FLOATING_IMAGE_INLINED'];
|
|
5
|
+
/**
|
|
6
|
+
* Word → PDF with engine selection, for Node surfaces (CLI, MCP):
|
|
7
|
+
* - native: built-in engine, fast and dependency-free.
|
|
8
|
+
* - libreoffice: a local LibreOffice install, for maximum fidelity.
|
|
9
|
+
* - auto: native, unless it had to drop content and LibreOffice is installed.
|
|
10
|
+
* Both engines run on this machine; nothing is uploaded.
|
|
11
|
+
*/
|
|
12
|
+
export async function convertWord(docx, opts = {}) {
|
|
13
|
+
const engine = opts.engine ?? 'auto';
|
|
14
|
+
if (engine === 'libreoffice')
|
|
15
|
+
return viaLibreOffice(docx);
|
|
16
|
+
const native = await wordToPdf(docx, opts);
|
|
17
|
+
if (engine === 'native' || !native.warnings.some((w) => CONTENT_LOSS.includes(w)))
|
|
18
|
+
return native;
|
|
19
|
+
const { findLibreOffice } = await import('./libreoffice.js');
|
|
20
|
+
if (!(await findLibreOffice()))
|
|
21
|
+
return native;
|
|
22
|
+
try {
|
|
23
|
+
return await viaLibreOffice(docx);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return native;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function viaLibreOffice(docx) {
|
|
30
|
+
const { libreOfficeToPdf } = await import('./libreoffice.js');
|
|
31
|
+
const pdf = await libreOfficeToPdf(docx);
|
|
32
|
+
const pageCount = (await PDFDocument.load(pdf, { updateMetadata: false })).getPageCount();
|
|
33
|
+
return { pdf, pageCount, warnings: [], engine: 'libreoffice' };
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=convert.js.map
|
package/dist/fonts.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { PDFDocument, PDFFont } from 'pdf-lib';
|
|
2
|
+
import type { RunStyle } from './model.js';
|
|
3
|
+
/**
|
|
4
|
+
* Open fonts that are metric-compatible with the common Office fonts, so line breaks and
|
|
5
|
+
* page counts stay close to Word's. All are SIL OFL 1.1, distributed through Fontsource.
|
|
6
|
+
*/
|
|
7
|
+
export type Family = 'carlito' | 'caladea' | 'arimo' | 'tinos' | 'cousine' | 'noto-sans-symbols-2';
|
|
8
|
+
export declare function familyFor(name: string): Family;
|
|
9
|
+
/** Loads a font file such as ("carlito", "carlito-latin-400-normal.woff"). Return undefined if it does not exist. */
|
|
10
|
+
export type FontLoader = (family: Family, file: string) => Promise<Uint8Array | undefined>;
|
|
11
|
+
/** Default loader for Node: reads the files from the installed @fontsource packages. */
|
|
12
|
+
export declare const nodeFontLoader: FontLoader;
|
|
13
|
+
export interface Metrics {
|
|
14
|
+
ascent: number;
|
|
15
|
+
descent: number;
|
|
16
|
+
lineGap: number;
|
|
17
|
+
}
|
|
18
|
+
export interface Segment {
|
|
19
|
+
text: string;
|
|
20
|
+
font: PDFFont;
|
|
21
|
+
}
|
|
22
|
+
/** Embeds only the font files and glyphs a document needs, with per-character fallback across subsets. */
|
|
23
|
+
export declare class FontManager {
|
|
24
|
+
private doc;
|
|
25
|
+
private loader;
|
|
26
|
+
private faces;
|
|
27
|
+
missingGlyphs: boolean;
|
|
28
|
+
constructor(doc: PDFDocument, loader: FontLoader);
|
|
29
|
+
private key;
|
|
30
|
+
/** Loads every font needed for the given (style, text) pairs. Call before layout. */
|
|
31
|
+
prepare(uses: {
|
|
32
|
+
style: RunStyle;
|
|
33
|
+
text: string;
|
|
34
|
+
}[]): Promise<void>;
|
|
35
|
+
private facesFor;
|
|
36
|
+
metrics(style: RunStyle): Metrics;
|
|
37
|
+
/** Splits text into runs drawable with a single embedded font; unknown characters become "?". */
|
|
38
|
+
segment(text: string, style: RunStyle): Segment[];
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Fonts for stamping text with characters outside the standard PDF fonts (✓, Greek, Cyrillic, Vietnamese),
|
|
42
|
+
* in fallback order. For @hilvana/core text operations (`fonts` option).
|
|
43
|
+
*/
|
|
44
|
+
export declare function fallbackTextFonts(loader?: FontLoader): Promise<Uint8Array[]>;
|
|
45
|
+
//# sourceMappingURL=fonts.d.ts.map
|
package/dist/fonts.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import fontkit from '@pdf-lib/fontkit';
|
|
2
|
+
/** Last-resort fonts for symbols no text font has (✓ ✗ ☐ ★ ● → …). */
|
|
3
|
+
const SYMBOL_FILES = ['noto-sans-symbols-2-symbols-400-normal.woff', 'noto-sans-symbols-2-math-400-normal.woff'];
|
|
4
|
+
const SUBSETS = ['latin', 'latin-ext', 'greek', 'greek-ext', 'cyrillic', 'cyrillic-ext', 'vietnamese', 'hebrew'];
|
|
5
|
+
export function familyFor(name) {
|
|
6
|
+
const n = name.toLowerCase();
|
|
7
|
+
if (/courier|consolas|mono|code|lucida console|menlo/.test(n))
|
|
8
|
+
return 'cousine';
|
|
9
|
+
if (/cambria|georgia|garamond|book antiqua|palatino|constantia/.test(n))
|
|
10
|
+
return 'caladea';
|
|
11
|
+
if (/times|serif|baskerville|minion/.test(n))
|
|
12
|
+
return 'tinos';
|
|
13
|
+
if (/arial|helvetica|verdana|tahoma|trebuchet|liberation sans|roboto|open sans|segoe/.test(n))
|
|
14
|
+
return 'arimo';
|
|
15
|
+
return 'carlito'; // Calibri, Aptos and anything unknown
|
|
16
|
+
}
|
|
17
|
+
/** Default loader for Node: reads the files from the installed @fontsource packages. */
|
|
18
|
+
export const nodeFontLoader = async (family, file) => {
|
|
19
|
+
const { createRequire } = await import('node:module');
|
|
20
|
+
const { readFile } = await import('node:fs/promises');
|
|
21
|
+
const path = await import('node:path');
|
|
22
|
+
const require = createRequire(import.meta.url);
|
|
23
|
+
try {
|
|
24
|
+
const pkgJson = require.resolve(`@fontsource/${family}/package.json`);
|
|
25
|
+
return new Uint8Array(await readFile(path.join(path.dirname(pkgJson), 'files', file)));
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
/** Embeds only the font files and glyphs a document needs, with per-character fallback across subsets. */
|
|
32
|
+
export class FontManager {
|
|
33
|
+
doc;
|
|
34
|
+
loader;
|
|
35
|
+
faces = new Map();
|
|
36
|
+
missingGlyphs = false;
|
|
37
|
+
constructor(doc, loader) {
|
|
38
|
+
this.doc = doc;
|
|
39
|
+
this.loader = loader;
|
|
40
|
+
doc.registerFontkit(fontkit);
|
|
41
|
+
}
|
|
42
|
+
key(style) {
|
|
43
|
+
return `${familyFor(style.font)}-${style.bold ? 700 : 400}-${style.italic ? 'italic' : 'normal'}`;
|
|
44
|
+
}
|
|
45
|
+
/** Loads every font needed for the given (style, text) pairs. Call before layout. */
|
|
46
|
+
async prepare(uses) {
|
|
47
|
+
const byKey = new Map();
|
|
48
|
+
for (const u of uses) {
|
|
49
|
+
const k = this.key(u.style);
|
|
50
|
+
const entry = byKey.get(k) ?? { style: u.style, chars: new Set() };
|
|
51
|
+
for (const ch of u.text)
|
|
52
|
+
entry.chars.add(ch.codePointAt(0));
|
|
53
|
+
byKey.set(k, entry);
|
|
54
|
+
}
|
|
55
|
+
for (const [k, { style, chars }] of byKey) {
|
|
56
|
+
if (this.faces.has(k))
|
|
57
|
+
continue;
|
|
58
|
+
const family = familyFor(style.font);
|
|
59
|
+
const weight = style.bold ? 700 : 400;
|
|
60
|
+
const italic = style.italic ? 'italic' : 'normal';
|
|
61
|
+
const faces = [];
|
|
62
|
+
const pending = new Set([...chars].filter((c) => c > 32));
|
|
63
|
+
for (const subset of SUBSETS) {
|
|
64
|
+
if (faces.length > 0 && pending.size === 0)
|
|
65
|
+
break;
|
|
66
|
+
const bytes = await this.loader(family, `${family}-${subset}-${weight}-${italic}.woff`);
|
|
67
|
+
if (!bytes)
|
|
68
|
+
continue;
|
|
69
|
+
const kit = fontkit.create(bytes);
|
|
70
|
+
const covers = [...pending].filter((c) => kit.hasGlyphForCodePoint(c));
|
|
71
|
+
if (faces.length > 0 && covers.length === 0)
|
|
72
|
+
continue;
|
|
73
|
+
const pdf = await this.doc.embedFont(bytes, { subset: true });
|
|
74
|
+
faces.push({ pdf, kit });
|
|
75
|
+
covers.forEach((c) => pending.delete(c));
|
|
76
|
+
}
|
|
77
|
+
if (faces.length === 0)
|
|
78
|
+
throw new Error(`No font files found for ${family}. Is @fontsource/${family} installed?`);
|
|
79
|
+
for (const file of SYMBOL_FILES) {
|
|
80
|
+
if (pending.size === 0)
|
|
81
|
+
break;
|
|
82
|
+
const bytes = await this.loader('noto-sans-symbols-2', file);
|
|
83
|
+
if (!bytes)
|
|
84
|
+
continue;
|
|
85
|
+
const kit = fontkit.create(bytes);
|
|
86
|
+
const covers = [...pending].filter((c) => kit.hasGlyphForCodePoint(c));
|
|
87
|
+
if (covers.length === 0)
|
|
88
|
+
continue;
|
|
89
|
+
faces.push({ pdf: await this.doc.embedFont(bytes, { subset: true }), kit });
|
|
90
|
+
covers.forEach((c) => pending.delete(c));
|
|
91
|
+
}
|
|
92
|
+
if (pending.size > 0)
|
|
93
|
+
this.missingGlyphs = true;
|
|
94
|
+
this.faces.set(k, faces);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
facesFor(style) {
|
|
98
|
+
const f = this.faces.get(this.key(style));
|
|
99
|
+
if (!f)
|
|
100
|
+
throw new Error(`Font not prepared: ${this.key(style)}`);
|
|
101
|
+
return f;
|
|
102
|
+
}
|
|
103
|
+
metrics(style) {
|
|
104
|
+
const k = this.facesFor(style)[0].kit;
|
|
105
|
+
return { ascent: k.ascent / k.unitsPerEm, descent: Math.abs(k.descent) / k.unitsPerEm, lineGap: k.lineGap / k.unitsPerEm };
|
|
106
|
+
}
|
|
107
|
+
/** Splits text into runs drawable with a single embedded font; unknown characters become "?". */
|
|
108
|
+
segment(text, style) {
|
|
109
|
+
const faces = this.facesFor(style);
|
|
110
|
+
const out = [];
|
|
111
|
+
for (const ch of text) {
|
|
112
|
+
const cp = ch.codePointAt(0);
|
|
113
|
+
let face = faces.find((f) => f.kit.hasGlyphForCodePoint(cp));
|
|
114
|
+
let c = ch;
|
|
115
|
+
if (!face) {
|
|
116
|
+
face = faces[0];
|
|
117
|
+
c = cp === 0xa0 ? ' ' : '?';
|
|
118
|
+
}
|
|
119
|
+
const last = out[out.length - 1];
|
|
120
|
+
if (last && last.font === face.pdf)
|
|
121
|
+
last.text += c;
|
|
122
|
+
else
|
|
123
|
+
out.push({ text: c, font: face.pdf });
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Fonts for stamping text with characters outside the standard PDF fonts (✓, Greek, Cyrillic, Vietnamese),
|
|
130
|
+
* in fallback order. For @hilvana/core text operations (`fonts` option).
|
|
131
|
+
*/
|
|
132
|
+
export async function fallbackTextFonts(loader = nodeFontLoader) {
|
|
133
|
+
const out = [];
|
|
134
|
+
for (const subset of ['latin', 'latin-ext', 'greek', 'cyrillic', 'vietnamese']) {
|
|
135
|
+
const bytes = await loader('carlito', `carlito-${subset}-400-normal.woff`);
|
|
136
|
+
if (bytes)
|
|
137
|
+
out.push(bytes);
|
|
138
|
+
}
|
|
139
|
+
for (const file of SYMBOL_FILES) {
|
|
140
|
+
const bytes = await loader('noto-sans-symbols-2', file);
|
|
141
|
+
if (bytes)
|
|
142
|
+
out.push(bytes);
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
//# sourceMappingURL=fonts.js.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { wordToPdf, type WordToPdfOptions, type WordToPdfResult, type WordWarning } from './word.js';
|
|
2
|
+
export { convertWord, type WordEngine } from './convert.js';
|
|
3
|
+
export { findLibreOffice, libreOfficeToPdf } from './libreoffice.js';
|
|
4
|
+
export { DOCX_LIMITS, DocxError, isDocx, parseDocx } from './parse.js';
|
|
5
|
+
export { fallbackTextFonts, familyFor, nodeFontLoader, type Family, type FontLoader } from './fonts.js';
|
|
6
|
+
export type * from './model.js';
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { wordToPdf } from './word.js';
|
|
2
|
+
export { convertWord } from './convert.js';
|
|
3
|
+
export { findLibreOffice, libreOfficeToPdf } from './libreoffice.js';
|
|
4
|
+
export { DOCX_LIMITS, DocxError, isDocx, parseDocx } from './parse.js';
|
|
5
|
+
export { fallbackTextFonts, familyFor, nodeFontLoader } from './fonts.js';
|
|
6
|
+
//# sourceMappingURL=index.js.map
|
package/dist/layout.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { PDFDocument, type PDFPage } from 'pdf-lib';
|
|
2
|
+
import { FontManager } from './fonts.js';
|
|
3
|
+
import type { Block } from './model.js';
|
|
4
|
+
import type { ParsedDocx } from './parse.js';
|
|
5
|
+
/** Page numbers for PAGE / NUMPAGES fields while laying out headers and footers. */
|
|
6
|
+
interface FieldValues {
|
|
7
|
+
page?: number;
|
|
8
|
+
total?: number;
|
|
9
|
+
}
|
|
10
|
+
/** Something with a height that can be drawn at a position; the unit of pagination. */
|
|
11
|
+
interface Slice {
|
|
12
|
+
height: number;
|
|
13
|
+
draw: (page: PDFPage, x: number, top: number) => void;
|
|
14
|
+
/** Collapses at the top of a page (paragraph spacing). */
|
|
15
|
+
spacer?: boolean;
|
|
16
|
+
breakBefore?: boolean;
|
|
17
|
+
keepWithNext?: boolean;
|
|
18
|
+
/** Table header row. */
|
|
19
|
+
header?: boolean;
|
|
20
|
+
/** Slices to draw first when this slice starts a new page (repeated table headers). */
|
|
21
|
+
repeat?: Slice[];
|
|
22
|
+
}
|
|
23
|
+
export declare class LayoutEngine {
|
|
24
|
+
private doc;
|
|
25
|
+
private fonts;
|
|
26
|
+
private model;
|
|
27
|
+
private images;
|
|
28
|
+
readonly warnings: Set<string>;
|
|
29
|
+
constructor(doc: PDFDocument, fonts: FontManager, model: ParsedDocx);
|
|
30
|
+
prepare(): Promise<void>;
|
|
31
|
+
private textAtoms;
|
|
32
|
+
private atoms;
|
|
33
|
+
private lineMetrics;
|
|
34
|
+
private layoutParagraph;
|
|
35
|
+
private drawLine;
|
|
36
|
+
private paragraphSlices;
|
|
37
|
+
private tableSlices;
|
|
38
|
+
measureBlocks(blocks: Block[], width: number, fields?: FieldValues): Slice[];
|
|
39
|
+
/** Lays out the whole document into new pages of `doc` and returns the page count. */
|
|
40
|
+
render(): number;
|
|
41
|
+
}
|
|
42
|
+
export {};
|
|
43
|
+
//# sourceMappingURL=layout.d.ts.map
|