DOCX import and exportDocument
Open and save Word documents in the browser or in Node.js with Birch UI Document Editor, with a fidelity matrix, the import report, the package validator and the test corpus.
Word documents#
The DOCX reader and writer are written for this product and run on the client: no conversion server, no network access and no WebAssembly.
fileInput.addEventListener('change', async () => {
await editor.importDocx(fileInput.files![0]); // File, Blob, ArrayBuffer or Uint8Array
});
const blob = await editor.exportDocx(); // application/vnd.openxmlformats-officedocument.wordprocessingml.document
await editor.downloadDocx('Master Services Agreement'); // saves "Master Services Agreement.docx"The same functions work without an editor, including in Node.js:
import { docxToDocument, documentToDocx, readDocx } from '@birchui/document';
const data = await docxToDocument(bytes); // DocumentData
const { document, report, warnings } = await readDocx(bytes); // report lists what was modelled, preserved and dropped
const output = await documentToDocx(data, { trackRevisions: true });Fidelity#
Import and export follow two rules. What the editor models is editable, and everything else in the file is kept and written back unchanged. And what you do not touch is not rewritten: every paragraph, table and content control at the top level of the body, every section, header, footer, note and comment that is the same as when the file was opened is written with its original XML, byte for byte. See Round trip at the XML level.
Each row of the matrix has one of three statuses:
- Modelled: read into
DocumentData, editable through the API (and, where the editing guides say so, in the interface), and written from the model. - Preserved: kept as the original XML and written back in place. It survives a round trip but cannot be changed here.
- Dropped or simplified: not kept, or kept as plain text.
| Feature | Status |
|---|---|
Paragraph, character, table and numbering styles with basedOn chains, linked styles, document defaults, theme fonts and theme colours with tint and shade |
Modelled; the resolved values are in DocumentData.styles, the original style sheet is written back |
| Bold, italic, underline, strikethrough, super- and subscript, fonts, sizes, colours, highlight | Modelled |
| Other run properties (small caps, spacing, language, East Asian fonts, theme references, character styles) | Preserved per run; the character style and the theme colour reference stay when the run is rebuilt after an edit |
| Alignment, spacing, exact and minimum line height, indents, tab stops with leaders, borders, shading, keep with next, keep lines, widow control, contextual spacing, outline level, right-to-left | Modelled |
Numbering: abstract definitions, instances, level and start overrides, restarts, lvlText patterns, number formats, legal numbering, numbering linked to heading styles |
Modelled in DocumentData.numbering; numberingLabels() computes every label |
| Sections: page size, orientation, margins, gutter, columns (count, gap, separator, unequal widths), break type, page number format and restart, vertical alignment, line numbering | Modelled |
| Headers and footers: default, first page and even pages for every section, inherited when a section defines none | Modelled |
| Footnotes and endnotes with block content, custom marks, separators and numbering settings | Modelled |
Fields: PAGE, NUMPAGES, DATE, TIME, REF, PAGEREF, SEQ, IF, MERGEFIELD, HYPERLINK, TOC, simple and complex, nested |
Modelled with instruction and cached result; other fields keep their instruction and result. The stored result of PAGE and NUMPAGES is kept by documentToDocx. exportDocx() knows the layout and writes its pages into every field and table of contents it rebuilds: the page count into NUMPAGES, the first page that shows a header or footer into its PAGE fields, the page of the bookmark into PAGEREF and the page of each heading into the table of contents entries. Blocks, headers and footers that are written back from the imported file keep the results they came with. Pass the same numbers to documentToDocx yourself with pageCount and pages: { bookmarks, headings, headerFooter } |
| Tables of contents | Modelled with the entries, their page numbers and the paragraph format of each entry (style, indent, tab stops with leaders), so a rebuilt list looks like the imported one |
| Page and column breaks inside a paragraph | Modelled; the break is written back into the paragraph it was typed in |
| Bookmarks, including ranges across paragraphs, and cross-references | Modelled |
| Content controls: plain text, rich text, drop-down, combo box, date, checkbox, picture, repeating section, group; tag, title, lock, placeholder, data binding; block, inline, row and cell level | Modelled |
| Tables: nested tables, merged cells, header rows, row height rules, rows that cannot split, cell margins, borders, shading, vertical alignment, text direction, table style and its conditional shading, width, indent, alignment | Modelled |
Floating table positions, row and cell property changes, row offsets written as gridBefore and gridAfter |
Preserved (row offsets import as empty cells) |
| Pictures: inline and floating with wrap mode, position, crop, rotation and flip | Modelled |
| Text boxes | Text modelled as blocks; the shape is preserved with a preview (geometry, fill, line) |
| Shapes, groups, canvases, VML | Preserved |
| Charts with one plot of columns, bars, lines, areas, a pie, a doughnut or points | Modelled: drawn from the cached data, editable, written back unchanged when not edited and as a new chart part with an embedded workbook when edited |
| Other charts and SmartArt | Preserved with their parts and relationships; where the file stores a picture for older readers, the drawing node carries it as fallback (a data URL) |
Embedded files: Excel, Word and PowerPoint packages, PDF, and Package objects holding any file |
Modelled as embedded_object with the file name, type, ProgID, bytes and picture; see Embedded objects. Linked objects are preserved |
| Pictures in EMF and WMF | Modelled; drawn as SVG on screen, the metafile is written back unchanged |
| Equations | Preserved; equations from Word cannot be edited |
| Tracked insertions, deletions and moves, tracked formatting changes of runs and paragraphs, tracked paragraph marks, tracked table rows and cells | Modelled; the earlier formatting of a tracked change is kept exactly as stored |
| Comments with replies, resolved state and stable identifiers | Modelled |
Mentions in comments and comment authors (people.xml with presence information) |
Modelled: mentions on a comment or reply holds the range, name and e-mail address of each mention, and DocumentData.people lists the authors |
| Document protection (read-only, comments, tracked changes, forms) with its hash attributes | Modelled in DocumentData.protection; the password hash is kept, not computed |
| Document properties (title, subject, author, keywords, description, category, revision, dates) | Modelled; custom properties preserved |
Theme, latent styles, custom XML parts, glossary document, embedded fonts (obfuscated .odttf parts with their keys in the font table), web settings, unknown parts with their relationships and content types |
Preserved byte for byte |
Compatibility settings (w:compat flags and named w:compatSetting values) |
Preserved in the settings part and listed in DocumentData.settings.compat |
| Unknown elements in the body, in paragraphs and in runs, and unknown children of paragraph, run, table, row, cell and section properties | Preserved and written back in schema order |
Macros (vbaProject.bin) |
Dropped |
| Formatting inside comments, smart tag and custom XML wrappers, fields that span several paragraphs (except tables of contents) | Simplified: the text is kept |
readDocx returns an import report that lists what happened to the content of one file:
const { document, report, warnings } = await readDocx(bytes);
// report.modelled [{ feature: 'footnotes', count: 12 }, { feature: 'sections', count: 3 }, …]
// report.preserved [{ feature: 'charts', count: 2 }, { feature: 'theme', count: 1 }, …]
// report.dropped [{ feature: 'macros (vbaProject)', count: 1, note: 'Macros are removed on import' }]Sections#
The page setup and headers at the top level of DocumentData describe the first section. A section_break node in the content starts the next section and carries its page and headers; a header that a section does not define is inherited from the section before it. documentSections(data) returns every section with its resolved page setup, headers and block range.
Numbering, fields and styles#
import { numberingLabels, updateFields, documentSections } from '@birchui/document';
numberingLabels(data); // [{ path: [4], label: '2.1.', level: 1, numId: 3, format: 'decimal', suffix: 'tab', text: 'Fees' }, …]
const updated = updateFields(data, {
now: new Date(),
values: { vendor: { country: 'NL' } }, // used by IF fields with nested MERGEFIELD
pages: { go_live: 4, 'heading:0': 2 }, // page numbers for PAGEREF and for table of contents entries
});updateFields recomputes DATE, TIME, SEQ, REF, PAGEREF, IF and document property fields and rebuilds the entries of every table of contents. Page numbers are not computed here; pass them in pages, keyed by bookmark name, by heading:<index> or by heading text.
A paragraph that uses a style of the imported document keeps its name in the wordStyle attribute, and its other attributes hold only what differs from that style. The resolved formatting of every style is listed in DocumentData.styles.
Validation#
validateDocxPackage(bytes) checks a package without opening a word processor: well-formed XML, content types for every part, relationship targets, the order of child elements, unique identifiers of bookmarks, comments, revisions, drawings and notes, and that every referenced style, numbering instance, note, comment and relationship exists.
The order check uses the child sequences of the transitional schemas in ECMA-376 Part 1 for every container the writer emits: paragraph, run, table, row, cell and section properties, borders and cell margins, numbering definitions and levels, styles, settings and compatibility settings, content control properties, and inline and anchored drawings with their pictures. The package tests build documents that use every writer feature and assert that each element follows its sequence.
const result = await validateDocxPackage(await documentToDocx(data));
// { ok: true, issues: [] }The package tests run this check on every file they export.
Test corpus#
packages/document/scripts/validate-docx.mjs builds a corpus of 94 documents with 797 pages and checks every file. Set BIRCHUI_DOCX_OUT to a folder outside the repository; a run takes about 40 seconds.
| Producer | Source | Files |
|---|---|---|
| python-docx | generated documents | 34 |
| LibreOffice | the same documents saved as ODT and converted back | 34 |
| LibreOffice | templates that LibreOffice ships (letters, faxes, agendas, reports, CV, business card, index example, Japanese and Chinese defaults) | 19 |
| LibreOffice | flat ODT, HTML and RTF sources in scripts/corpus |
7 |
The generated documents include a master services agreement with multilevel numbering and cross-references, a research paper with footnotes, equations, captioned figures, a table of contents and a bibliography, a newsletter with columns, floating pictures and text boxes, a form with content controls, a mail-merge letter, a review copy with tracked insertions, deletions, moves, formatting changes and comment replies, nested and merged tables with vertical text, Arabic, Hebrew, East Asian and mixed-script documents, a document with four page sizes and orientations, a chart, a SmartArt diagram and an embedded workbook, and a 301-page handbook.
Each file is imported and exported, and the original, the export and a version rebuilt from the model alone are converted to PDF with LibreOffice. Every check is a gate: the script exits with an error when one fails.
| Check | Files that pass |
|---|---|
| Import and export without an error | 94 of 94 |
validateDocxPackage errors in the export |
none in 94 of 94 |
| Second import gives the same document | 94 of 94 |
| python-docx opens the export; paragraph, table and section counts, rows and columns of every table and the number of inline pictures match | 94 of 94 |
| Page count of the export against the original | equal in 94 of 94 |
| Page breaks at the same position (first and last 24 characters of each of the 797 pages) | 797 of 797 pages, 94 of 94 files |
| Text of the PDF | identical in 94 of 94 |
Numbering labels computed by numberingLabels() appear in the PDF |
94 of 94 |
| Rebuilt from the model alone: package validates, structure matches, page count and page breaks agree | 94 of 94 (797 of 797 pages) |
| Rebuilt from the model alone: text of the PDF | identical in 93 of 94 |
The one exception is listed in the KNOWN table of the script: LibreOffice writes each entry of a table of contents inside its PAGEREF field and loses the text of the first entry when it loads its own file. The rebuilt list has plain entries, so the first entry is shown.
The corpus is generated by LibreOffice and python-docx, and the comparison is rendered by LibreOffice. It has not yet been validated against Microsoft Word itself: no file written by Word is in the corpus and no export has been opened in Word, because the build machine has no copy of it. Expect real Word documents to exercise markup the corpus does not, and use the import report and the validator on your own files.
Layout compared with LibreOffice#
The round-trip gates above compare LibreOffice with LibreOffice. This section compares the editor's own layout in Chrome with the PDF LibreOffice makes from the same file, on the same machine with the same fonts. e2e/tests/document-fidelity.spec.ts opens every corpus file in the editor, waits for the layout, and checks for every page break that the text before it ends the same page and the text after it starts the same page in the LibreOffice PDF (the first and last 24 characters of the page body).
| Measure | Before | Now |
|---|---|---|
| Files | 94 (797 pages in LibreOffice) | 94 (797 pages) |
| Same number of pages | 84 of 94 | 90 of 94 |
| Page breaks at the same text | 654 of 712 (92%) | 684 of 706 (97%) |
| Files with every break in the same place | 79 of 94 | 85 of 94 |
Numbers that come from fields (clause and figure numbers, page references) are ignored when the text at a break is compared, because the editor and LibreOffice may both be right with a different number. The number of breaks is the larger page count of the two minus one, so it falls when page counts agree.
Files that differ (lo- are the LibreOffice-converted variants, py- the python-docx originals):
| File | Editor pages | LibreOffice pages | Breaks in the same place |
|---|---|---|---|
lo-master-services-agreement.docx |
14 | 14 | 7 of 13 |
lo-mixed-script-notice.docx |
1 | 2 | 0 of 1 |
lo-template-1simple.docx |
2 | 2 | 0 of 1 |
lo-template-5blue.docx |
3 | 3 | 1 of 2 |
lo-template-aw-3modern.docx |
2 | 2 | 0 of 1 |
lo-template-bus-classic-f.docx |
5 | 2 | 0 of 4 |
py-master-services-agreement.docx |
14 | 14 | 7 of 13 |
py-mixed-script-notice.docx |
1 | 2 | 0 of 1 |
py-price-list.docx |
4 | 5 | 3 of 4 |
The other files agree on every page break. The 22 breaks that differ have four causes:
| Cause | Breaks | Files |
|---|---|---|
| A paragraph inside a list item is not split between pages; the item moves as a whole, and a heading item moves with the item after it | 12 | master services agreement |
| LibreOffice templates built from frames, fixed-height tables and several sections | 7 | four templates |
| Arabic, Hebrew and East Asian text falls back to different fonts with taller lines in LibreOffice | 2 | mixed-script notice |
| The bold heading font that a table style gives its first column is not applied, so the rows are lower | 1 | price list |
The 36 breaks that were fixed had causes that the earlier version of this page described wrongly as the space after the last paragraph of a table cell. LibreOffice applies that space, and so does the editor. The real causes were measured on the 301-page handbook: lines were 0.05 pt too high because line heights were not cut to twentieths of a point, each table row was 0.25 pt too high because a half-point border is drawn one pixel wide, tables had 8 pt of space below them, and a page break in a paragraph of its own took no line. The rules are listed under Paragraph spacing.
The break rules have fixtures of their own. scripts/docx-breaks.py writes five documents and the same test compares their page breaks:
| File | Pages (editor and LibreOffice) | Breaks in the same place |
|---|---|---|
breaks-widow-orphan-on.docx |
9 | 8 of 8 |
breaks-widow-orphan-off.docx |
9 | 8 of 8 |
breaks-keep-with-next.docx |
14 | 13 of 13 |
breaks-keep-chain.docx |
10 | 9 of 9 |
breaks-keep-lines.docx |
7 | 6 of 6 |
Floating pictures are compared line by line. scripts/docx-floats.py writes 24 documents: square left, right and offset, tight, top and bottom, behind, in front, bottom of the margin, six with the picture inside the column (square on both sides, centred, text on the left only, on the larger side, and tight and through with a diamond-shaped wrap polygon), three with the picture above its anchor paragraph, four with centred, right-aligned and right-to-left text, two with the picture in a table cell and one with the picture at a page break. The test compares where every line, and every part of a line beside the picture, starts in the LibreOffice PDF: the same first word within 3 pt horizontally.
| File | Line starts in the same place | Largest horizontal difference | Largest vertical difference |
|---|---|---|---|
float-above-anchor.docx |
39 of 39 | 0.1 pt | 0.4 pt |
float-above-both.docx |
47 of 47 | 0.7 pt | 0.4 pt |
float-above-margin-top.docx |
39 of 39 | 0.7 pt | 0.4 pt |
float-behind.docx |
37 of 37 | 0.1 pt | 0.4 pt |
float-both-center.docx |
47 of 47 | 0.7 pt | 0.4 pt |
float-both-centred-text.docx |
47 of 47 | 1.6 pt | 0.4 pt |
float-both-largest.docx |
40 of 40 | 0.7 pt | 0.4 pt |
float-both-left-only.docx |
40 of 40 | 0.1 pt | 0.4 pt |
float-both-right-text.docx |
46 of 47 | 3.0 pt | 0.4 pt |
float-both-rtl-text.docx |
41 of 47 | 0.7 pt | 1.5 pt |
float-both-square.docx |
47 of 47 | 0.7 pt | 0.4 pt |
float-both-through-polygon.docx |
47 of 47 | 2.3 pt | 0.4 pt |
float-both-tight-polygon.docx |
47 of 47 | 1.6 pt | 0.4 pt |
float-cell-both.docx |
33 of 33 | 0.7 pt | 0.4 pt |
float-cell-side.docx |
23 of 23 | 0.7 pt | 0.4 pt |
float-in-front.docx |
37 of 37 | 0.1 pt | 0.4 pt |
float-margin-bottom.docx |
40 of 40 | 0.1 pt | 0.4 pt |
float-page-break.docx |
41 of 41 | 0.7 pt | 0.4 pt |
float-side-centred-text.docx |
40 of 40 | 1.5 pt | 0.4 pt |
float-square-left.docx |
40 of 40 | 0.1 pt | 0.4 pt |
float-square-offset.docx |
39 of 39 | 0.1 pt | 0.4 pt |
float-square-right.docx |
40 of 40 | 0.1 pt | 0.4 pt |
float-tight-right.docx |
40 of 40 | 0.1 pt | 0.4 pt |
float-top-bottom.docx |
31 of 31 | 0.1 pt | 0.9 pt |
968 of 975 line starts agree in Chrome. Five of the seven that differ are the full stop that ends a right-to-left paragraph, which the reference PDF lists as a line of its own; one is a comma at the end of the text on one side of the picture in a right-to-left paragraph; one is the last word of a line below the picture in the right-aligned document. The largest vertical difference fell from 2.2 pt to 0.9 pt with the line heights in twentieths of a point (1.5 pt in the right-to-left document). The comparison is not run in Firefox, where lines are slightly shorter and drift by about half a line over a page.
Round trip at the XML level#
On import the reader keeps the original document.xml and, for every top-level block of the body, where its XML starts and ends and a fingerprint of the model nodes that came from it. A block here is what the model treats as one: a paragraph, a table, a content control, a whole list, a table of contents, or a paragraph together with the section break it carries. Headers, footers, notes and comments are kept the same way, part by part.
On export the writer compares fingerprints. A block whose nodes are unchanged is written with its original XML; a block that changed, moved in from elsewhere or is new is generated from the model. The root element with its namespace declarations, the relationship ids, the numbering and the styles stay as they were, so the two kinds of block sit side by side:
- A new relationship, note, bookmark, tracked change or drawing gets an id that the kept blocks do not use.
- Notes that are still referenced keep their id and their XML. A new note is added after them.
- A header or footer that did not change is the original part. One that changed is written as a new part and the section that uses it is rebuilt.
comments.xmland its companion parts are the originals while no comment was added, edited, resolved or removed.[Content_Types].xml,_rels/.relsanddocument.xml.relsare the originals when the export has the same parts and relationships.
A kept block must still be valid. A block is rebuilt when its original XML breaks the element order of the schema, refers to a style that the style sheet does not define, or repeats an id that an earlier block already uses. That keeps validateDocxPackage clean for every export, and it means a file from a producer that writes such markup is repaired only where the markup is wrong.
await documentToDocx(data); // unchanged blocks byte for byte, invalid ones rebuilt (default)
await documentToDocx(data, { preserveSource: 'exact' }); // unchanged blocks byte for byte, also invalid ones
await documentToDocx(data, { preserveSource: false }); // everything generated from the modelDocumentData.docx.source holds the original XML. It roughly doubles the size of the text of a document in memory; delete it (data.docx.source = null) when you do not need the guarantee. It works through the editor: importDocx, edits and exportDocx keep every block the edits did not reach.
scripts/docx-idempotence.mjs imports and exports every corpus file without touching it and compares each XML part with the original, byte for byte.
| Measure | Before | Now |
|---|---|---|
word/document.xml identical |
3 of 94 | 79 of 94 |
word/document.xml identical, of the 79 originals without validator errors |
3 of 79 | 79 of 79 |
word/document.xml identical with preserveSource: 'exact' |
3 of 94 | 94 of 94 |
| Top-level blocks of the body identical | not measured | 6,744 of 6,775 (99.5%) |
| Headers and footers identical | 13 of 92 | 92 of 92 |
word/styles.xml, word/settings.xml, word/fontTable.xml, word/theme/theme1.xml, word/numbering.xml |
all | all |
Footnotes, endnotes, comments, document.xml.rels, _rels/.rels |
rebuilt | identical except in 2 of the 15 repaired files, whose comments are rebuilt |
[Content_Types].xml identical |
0 of 94 | 92 of 94 |
| All XML parts identical | 1,076 of 1,361 | 1,246 of 1,361 |
The 15 files that are not identical are files whose own markup fails the validator: 13 written by the corpus generator with elements in the wrong order (w:bidiVisual after w:tblLook, w:pgNumType after w:docGrid, w:pBdr after w:jc) or with runs that use a Hyperlink, CommentReference or Style character style the style sheet does not define, and two written by LibreOffice with the same id on every tracked change. In those files 31 of 326 blocks are rebuilt and the rest are kept. The remaining differences are docProps/core.xml in every file, because the modification date is written, and [Content_Types].xml in two files: one of the 15, and one template whose original has no content type for its WMF picture.
After an edit to one paragraph, every other top-level block is identical. The package tests check this on the ten committed fixtures (test/docx-source.test.ts), including a pass through the editor.
Embedded fonts are covered by scripts/docx-fonts.py, which writes a document with two obfuscated fonts the way Word stores them. The fonts, the font table and its relationships come back unchanged, and LibreOffice renders the export with the embedded fonts.
A second reader#
scripts/docx-second-reader.mjs opens every original and every export with Apache POI (set BIRCHUI_POI_DIR to a folder with the POI jars) and compares what POI reads.
| Check | Before | Now | Rebuilt from the model (preserveSource: false) |
|---|---|---|---|
| Export opens in Apache POI 5.2.5 | 94 of 94 | 94 of 94 | 94 of 94 |
| Same number of paragraphs, tables and table cells | 94 of 94 | 94 of 94 | 94 of 94 |
| Same number of pictures | 94 of 94 | 94 of 94 | 94 of 94 |
| Same extracted text | 81 of 94 | 94 of 94 | 91 of 94 |
All 13 earlier differences were stored field results: PAGE and NUMPAGES in headers and footers were written as 1. They are gone because untouched headers are the original parts, and because a rebuilt field now keeps its stored result.
The last column is the harder case, where nothing is kept and every block is generated. Three files differ there:
py-feature-mix.docx: anIFfield with a nestedMERGEFIELDstores the textNLbetween the two; the rebuilt field has the instruction and the result without it.lo-quarterly-review.docx: the rebuilt comment has aw:commentReferencerun, so POI adds the comment text where the original, written by LibreOffice without that run, gives none.lo-template-bus-classic-f.docx: aPAGEfield in the body has an empty stored result; the rebuilt field has the result 1.
A picture inside a rebuilt text box uses the relationship the shape already has for it, so the picture is stored once and no relationship is added.
Addresses in imported files#
A document from outside can carry a link that runs script. Every address is sorted into one of three groups before it reaches the model or the page. Tabs, line breaks, control characters, zero-width characters and leading spaces are removed before the scheme is read, and the scheme is compared without regard to case, so java	script: and JaVaScRiPt: are caught too.
| Address | In the document | On the page and in documentToHtml |
In a saved DOCX |
|---|---|---|---|
javascript:, vbscript:, data: |
Removed. The words of the link stay as ordinary text | Text | Not written |
http:, https:, mailto:, tel:, relative addresses, #bookmark, and the schemes in linkSchemes |
A link | A link that can be followed | Written |
Any other scheme: file:, ftp:, sms:, msteams:, slack:, onenote: and so on |
A link mark with the original address and inert: true |
A blocked address: a span, never <a href> |
Written back unchanged |
- Script addresses are removed from a DOCX package before anything reads it. The relationship is deleted, and the
w:hyperlinkelement or theHYPERLINKfield around the visible runs is removed, so the words become ordinary runs that can be edited, in the model and in the saved file in both export modes. A link stored as a relationship and a link stored as a field import the same way. Fields are found with the XML parser and read with the field parser the importer uses, so a lower-case field name, a character reference, an instruction split over severalw:instrTextruns or another namespace prefix makes no difference.report.droppedhas an entryhyperlinks with a script addresswith thecountand anotethat lists the first twenty addresses, andwarningshas one line with the same text. - Blocked addresses keep their link. A shared-drive link (
file://fileserver/finance/q3-budget.xlsx), an FTP address or an application link is ordinary in business documents, so it stays in the document JSON and is written back to DOCX and OpenDocument exactly as it was read. The editor draws it with a dotted underline as aspanwithrole="link", the description blocked link and a tooltip that shows the address. A click or Ctrl+click does nothing, the address is announced when the caret enters the link, and a copy puts nohrefon the clipboard; pasting it back keeps the address.documentToHtmlwrites<span data-blocked-address="…">, whichhtmlToDocumentreads back; Markdown and PDF export write the text only. linkSchemesextends the list of schemes that can be followed, for hosts that want it:createDocumentEditor(element, { linkSchemes: ['file', 'ftp', 'sms', 'msteams'] })anddocumentToHtml(document, { linkSchemes: ['file'] }). The editor reads it when it is created.javascript,vbscriptanddataare ignored in this list and can never be enabled.- Pictures may be
data:image/…orblob:URLs, which are drawn, orhttp(s)and relative URLs, which are kept in the document but not requested: the editor draws a placeholder with the alternative text and leaves the address indata-remote-src. SetallowRemoteImages: trueto draw them, or passresolveImage(url)and return adata:image/…URL your application fetched. Any other picture source is cleared.
The check runs in the link mark and the image node of the editor (reading from and writing to the page), in normalizeDocument (so setJSON and content are covered), in the DOCX reader, in the Markdown, HTML, RTF and OpenDocument importers, in paste, in collaboration steps, and in the HTML, Markdown, DOCX and PDF writers. importHtml parses with DOMParser in an inert document, so event handlers and pictures in the pasted markup never load. sanitizeHref(value, linkSchemes?) returns an address only when it can be followed, and sanitizeImageSrc(value) does the same for pictures; both are exported for your own code.
Limits on archives#
A .docx or .odt file is a zip archive, and a small file can claim to expand to gigabytes. The reader checks the directory before it inflates anything, inflates one entry at a time, and stops an entry the moment it grows past its declared size.
| Limit | Default | Error code |
|---|---|---|
maxEntries |
10,000 | too-many-entries |
maxEntryBytes |
512 MiB | entry-too-large |
maxRatio (checked for entries above 1 MiB) |
200 | ratio-too-high |
maxTotalBytes |
1 GiB | archive-too-large |
import { readDocx, ZipLimitError } from '@birchui/document/docx';
try {
await readDocx(bytes, { limits: { maxTotalBytes: 64 * 1024 * 1024 } });
} catch (error) {
if (error instanceof ZipLimitError) console.warn(error.code, error.entryName, error.limit, error.actual);
else throw error;
}limits is accepted by readDocx, docxToDocument, odtToDocument, validateDocxPackage, importDocx(file, { limits }) and as the editor option limits. Infinity turns a limit off; a negative value or NaN logs a warning and keeps the default. XML nested more than 512 elements deep is refused, and entities declared in a DOCTYPE are never expanded.
Other unreadable input fails with DocumentFormatError: code is encrypted-or-legacy-doc for an OLE compound file (a password-protected document or a legacy .doc), not-a-zip, not-a-word-document, encrypted-entry or xml-too-deep.
Document size#
DocumentData keeps the parts of the source file it does not model, so that export can write them back. Large text parts (above 4 kB) are kept as the base64 of their original compressed bytes ({ deflate, size }) instead of as text. For the 37 kB invoice of the review the JSON went from 1,011,763 to 176,717 characters; 84 kB of that are the 164 modelled styles. A named version no longer repeats the package and numbering it shares with the open document and takes 94 kB there.
Limits#
- Being modelled means the data round-trips and is available in
DocumentData. How the editor displays each feature, and where the layout approximates Word, is listed in Limitations. - Password hashes of protected documents are preserved, not computed: a new password cannot be set.
readDocxdoes not read older.docfiles. UsedocToDocumentfor them, oreditor.openFile, which picks the reader from the bytes of the file; see Word 97–2003.
Other formats, printing and PDF#
Markdown, HTML, RTF and OpenDocument converters are described in Other formats, and printing and the PDF writer in PDF export and print.