Download the PHP package particle-academy/last-word without Composer

On this page you can find all versions of the php package particle-academy/last-word. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package last-word

LastWord

PHP package for reading and writing word-processing documents (.docx) from a JSON-friendly document model, with markdown bridges. Framework- agnostic, zero runtime dependencies (just ext-zip + ext-dom). Designed so WYSIWYG editors — react-fancy's Editor in particular — round-trip real Word files without a converter sandwich (mammoth → turndown → docx): one model, one engine, both directions.

Mirror package: @particle-academy/last-word (Node/TS) implements the exact same JSON model and Agent API, so a doc emitted by an agent works verbatim on either backend.

For agents. This package is listed on the Fancy MCP catalog server at https://ui.particle.academy/mcp (streamable HTTP, no API key; MCP id fancy-ui), with install commands and docs, alongside the rest of the kit. How an agent installs and uses this package is in AGENTS.md.

Why

DOCX, ODT and template archives enforce limits of 64 MiB input/part, 256 MiB expanded data, 16,384 members and 1000:1 expansion. Corrupt, duplicate, unsafe or unsupported entries raise LastWord\Exceptions\ArchiveRefused with a constant reason. Templates wrap it in TemplateException (getPrevious() retains the cause). Local document/template file input is bounded to 64 MiB too. Archive checks do not promise support for every document XML construct.

Sister project to holy-sheet (XLSX) and dark-slide (PPTX). The three share an "agent emits JSON, PHP writes a real Office document" pattern:

Document type Node mirror PHP package
Spreadsheets holy-sheet-js holy-sheet
Presentations dark-slide-js dark-slide
Documents last-word-js last-word

Quickstart

The Editor round-trip

The whole point: an agent (or a human in a WYSIWYG editor) works in markdown or the JSON model, and .docx is just a serialization at the edges.

The bridge is hand-rolled GFM (no external markdown dependency): headings, **bold** / *italic* / ~~strike~~ / `code`, links, ordered + unordered nested lists, tables, fenced code blocks, blockquotes, ![alt](src) images, --- rules — plus an <!-- pagebreak --> comment convention so page breaks survive the trip. Underline / colors / alignment have no markdown slot and drop on that path (they round-trip fine through .docx itself).

Document model

A Doc is a title plus a flat list of blocks; camelCase keys, plain associative arrays, identical in the Node mirror:

Runs (inline text spans) carry the formatting:

Blocks, discriminated by type:

Type Shape
heading { level: 1-6, runs }
paragraph { runs, align?: "left"\|"center"\|"right"\|"justify" }
list { ordered?, items: [{ runs, children? }] } — nesting to 6 levels
table { rows: [{ header?, cells: [{ blocks }] }] }
code { language?, text } — multiline, monospace, shaded
quote { blocks }
image { src: "data:image/png;base64,…", widthPx?, heightPx?, alt? }
chart { option: <ECharts option>, widthPx?, heightPx?, width? (% of column), numberFormat?, alt? } — a native, editable Word chart (bar / column / line / pie) with an embedded workbook; option is the same field dark-slide's chart takes
pageBreak { page? } — with page, the page changes from here on (see Mixed pages)
hr { }

Image dimensions are optional — the writer sniffs intrinsic size straight from the PNG IHDR / JPEG SOF bytes and caps at 6.5in page width keeping aspect.

Footnotes

A footnote is a run with text: "" and a footnote, placed where the reference mark goes:

The model carries no number: Word numbers the marks 1, 2, 3 in document order and sets each footnote at the foot of the page its mark is on, under a short rule and above the footer. A footnote's blocks are the body's vocabulary less chart and pageBreak (at any depth); a footnote may sit in a heading, a paragraph, a list item, a table cell or a quote, but not inside another footnote and not in a header or footer (validation refuses both; validateAndRepair drops them with a note, and moves text typed on the mark into a run of its own before it).

The writer emits word/footnotes.xml with the separator (w:id -1) and continuation separator (0) Word requires, w:footnotePr in settings, the FootnoteText / FootnoteReference styles, and the footnotes part's own relationships for its links and images. A document without a footnote is byte-identical to before. read() returns the same run for a .docx footnote from any producer; the .doc, .odt and .rtf readers still skip footnotes. Markdown, HTML, plain-text and portable export do not carry them yet: the mark vanishes there and the footnote's text is not exported.

Page geometry

page.margins takes top, right, bottom, left and the header and footer distances, header / footer: points from the top edge of the page to the header and from the bottom edge to the footer (Word's w:pgMar header / footer). Defaults: 72 a side, 36 a distance.

read() returns only the values that differ from those defaults, and no page at all when nothing does, so an absent margin means the default, not "none". A viewer gets all six numbers from Schema::pageMargins($doc). Where Word puts things: the header at header from the top, the body from top, the footer's last line at footer from the bottom, footnotes at the foot of the body (above bottom); Word pushes the body down when a header is taller than top - header leaves room for, and up when a footer is.

page takes size, orientation, margins, header, footer, and the same page decoration fine-print draws: background (#RRGGBB) and border ({style, width, color, inset}: a frame inset points from the page edge, width across, single by default; a double is two rules of a third each). They are written as Word's w:background and w:pgBorders. The field set is pinned against fine-print's by fancy-conformance doc-model/shared.

Headers and footers: a band, or blocks

page.header / page.footer is one of two forms, never both at once:

A blocks header takes every block type except chart and pageBreak, at any depth (a table cell in a header cannot hold one either), and not portable. In run text {page} and {pages} are live page fields, as in a band; in the body they stay literal. An empty blocks list asks for nothing, like an empty band.

Reading. read() returns the band form for a header or footer that is one paragraph of text and nothing else, exactly as it always has. A header that held a picture, several paragraphs, a table or a content control (Word's own page-number footer is one) comes back as blocks: the logo as an image block with a data: URL, the same as a body image; PAGE and NUMPAGES fields as {page} / {pages}; and a picture that sits before a paragraph's text in front of that paragraph. unrepresented then lists only what blocks cannot hold either: VML pictures, embedded objects, GIF / EMF and other formats outside the image block, linked or oversized images, text boxes (image), and charts (chart). Blocks this package writes are wrapped in a lastword:band content control, so a one-paragraph blocks band reads back as blocks rather than as a band.

Writing. A blocks band goes through the body's block renderer into header1.xml / footer1.xml with its own relationships file, so its image and link relationship ids are scoped to that part. Images share the document's media/image{n} numbering and drawing ids, so nothing collides with the body, the other band, or a letterhead carried by templateParts (template{n} media, drawing ids below ours). The document's own header still replaces the template's.

Hardening is the letterhead's. A header or footer image, whether an agent wrote it or read() took it from an upload, must be PNG or JPEG by its leading bytes as well as its type, at most 16 MiB, and at most 32 MiB across the header and footer. A src that is not a data: URL fails validation, and if it reaches the writer anyway it is written as its alt text: nothing is fetched. On read, a linked (external) picture, a header part over 2 MiB or one declaring a DOCTYPE is never read as blocks (the part falls back to the band reading and the report).

Named images: the host's logo, placed by name

The host registers images by name; the model places them by name, in the body, a footnote or a header or footer, and never carries the bytes or invents one:

Each image is PNG or JPEG bytes, a data URL, or {data, widthPx?, heightPx?, alt?}, checked as it is registered against imageLimits (maxBytes 5 MiB, maxWidthPx and maxHeightPx 4096, maxImages 32 by default, each a host setting); a refused one throws ImageRefused with a stable reason. A block's own widthPx / heightPx / alt win over the registered ones. An image: name nobody registered is a validation error with code: "image_unknown", from validate(), validateAndRepair() and toBytes() alike. A named image writes exactly what the same image as a data URL writes, and the Node package does the same thing byte for byte. Without images, the guide and the schema are exactly what they were.

First page and even pages (0.16.0)

page.firstHeader / page.firstFooter replace header / footer on the first page only (Word's "Different first page"); page.evenHeader / page.evenFooter replace them on even pages (Word's "Different odd and even pages"). Each takes either form above. Nothing existing changes: page.header is still every page, and with a firstHeader it is every page but the first.

read() returns the variants a document has in force: firstHeader only while w:titlePg is on, evenHeader only while w:evenAndOddHeaders is, never a variant that names the same part as the default, and {"blocks": []} for a page that shows no header while the default does. Footnotes stay refused in every band.

Fields in header and footer text (0.16.0)

token Word field cached result written
{page} / {pages} PAGE / NUMPAGES 1
{section} / {sectionpages} SECTION / SECTIONPAGES the section's number / 1
{author} AUTHOR meta.author, or nothing
{title} TITLE the document title, or nothing
{filename} FILENAME nothing
{date} / {time} DATE / TIME nothing
{date:FORMAT} / {time:FORMAT} DATE \@ "FORMAT" / TIME \@ "FORMAT" nothing

FORMAT is a Word date-time picture (yyyy-MM-dd, d MMMM yyyy, HH:mm): one or more characters, none of {, }, " or a backslash. Without one, the date and time show in the reader's locale. Names are lower-case and exact; anything else in braces ({Date}, {foo}, {date:}, {page:x}) stays literal text, and in the body every token is literal text.

Each is a live complex field in the band's formatting, the same mechanism {page} already used. The cached result is what a viewer, and Word until its fields update, shows: it is the value when the writer knows it and nothing when it does not, because writing the clock would make the same document write different bytes. LibreOffice computes all of them on load (checked: the date, the time, the author, the title, the file name, page and section numbers). read() maps any producer's field back to its token by its first word; a \@ picture the grammar can hold is kept and every other switch is dropped.

Document properties: meta

meta.author is Word's Author property (docProps/core.xml dc:creator) and what {author} shows. The title is the existing top-level title (dc:title), deliberately not meta.title: one slot, so the two can never disagree. validateAndRepair moves a meta.title to title.

Exchange: portable content and exports

last-word reads and writes portable content (fancyContent: 1), the plain-JSON format the document packages use to move content between each other (normative text: fancy-conformance suites/exchange/SPEC.md):

Exports are off by default. The host enables targets with an ExportPolicy; nothing an agent passes can enable one:

Targets: markdown, text, html (escaped, no scripts, links only http/https/mailto, images as data URIs), docx (from .doc, .odt, .rtf). pdf answers export_unavailable until the fine-print bridge ships.

Page count

Agent::layout() lays a document out the way the @particle-academy/last-word-ui viewer (0.3.0+) does, without a browser. That viewer draws Calibri and unspecified text in a bundled Carlito (metric-compatible with Calibri), so its pages are the same on every machine, and this matches them: on the shared fixtures, the page count, every page start and every measured line agree exactly.

Pass the options you write with: with a template, the document is laid out as it reads back (a first-page letterhead from templateFirstPageOnly takes its real height on page 1). Text in another font, code and band date fields are estimates, and approximate says so. PHP-first: the Node and Python packages do not have it yet.

API

Everything is on one static façade, LastWord\Agent, mirrored exactly in the Node package: validate (with heuristic repair), write and read, the markdown bridge, a JSON Schema for LLM tool registration, diffs, portable content and host-gated exports. The full method table is in AGENTS.md.

Rendering onto a house template

Every document used to come out in the built-in look, so an automation that produced a structurally correct .docx still needed a human to re-apply the house style. Pass a .dotx (or .docx) and it renders onto that template's typography instead:

It binds by style name, with nothing to configure. The document model already uses Word's own style ids, so a template that defines Normal, Title, Heading1..n, Quote, ListParagraph and Hyperlink binds on its own. The template's word/styles.xml and word/theme/theme1.xml are carried through verbatim; definitions it does not have (CodeBlock and InlineCode, or heading levels it omits) are supplied from the built-in set.

The theme travels with the styles deliberately. A style that names a theme colour or font resolves against whatever theme is in the package, so taking styles alone would give you the template's structure in the default's colours — a wrong answer that looks deliberate.

What the template does NOT bring:

its body a letterhead often arrives as a .docx with a sample letter in it; none of its text or images is taken
word/numbering.xml your lists reference numbering ids defined by this package; a template's would repoint them
word/settings.xml mostly w:rsid revision history, which would make output depend on a template's editing past (only w:evenAndOddHeaders is carried, when a carried even-page header needs it)

So list markers are still ours; the typography, colours and theme are the template's. The page setup is ours too, unless you ask for the letterhead.

Keeping a letterhead: templateParts

A customer's letterhead — a logo and address in the page header, a footer line, its own page size and margins — is the template's section. Name the parts to take:

part takes
styles word/styles.xml + the theme, as above. The default when templateParts is absent, so template alone does exactly what it always did
headers every header part the template's section references (default, first-page, even-page), byte for byte, with its images
footers the same for footers
page page size and orientation, the four margins, header/footer distances and gutter

The header and footer XML and their images are copied byte for byte; what is renamed is everything that could collide (parts become header{n}.xml / footer{n}.xml, images media/template{n}.{ext}, document relationship ids rIdTplHeader{n}), and drawing ids in your body start above the largest the letterhead uses. A first-page header carries w:titlePg with it; an even-page one carries w:evenAndOddHeaders.

Your document's own settings win, field by field. A page.header replaces the template's headers (all of them, first and even included); page.footer the same for footers; page.size, page.orientation and each of page.margins override that one value. Anything you leave unset is the template's. When the template has a first-page or even-page part and you set your own band for the other kind, your band is referenced for those pages too, so it is still on every page.

The letterhead on the first page only: templateFirstPageOnly.

The template's header and footer become Word's FIRST-page header and footer (w:titlePg on): the template's own first-page part when it has one in force, which is what it shows on page one, otherwise its default part. Its even part is not carried. Later pages get your page.header / page.footer, and nothing when you set none. A page.firstHeader of your own still wins over the template's. false or absent is the behaviour before the option existed, byte for byte; anything but a boolean throws TemplateException. The carried parts are header4.xml / footer4.xml (1-3 are your own bands by slot). read() returns such a letterhead as firstHeader / firstFooter, never header.

To write a read document back onto its own original, drop page.header and page.footer first: read() fills them (as a band or as blocks), and left in they are your own and win. Without a template, leave them in: the blocks form writes the logo and address back on its own.

A letterhead is a customer upload, so it is read as hostile. Anything that cannot be carried safely is refused with TemplateException rather than dropped (dropping a relationship would leave the part pointing at nothing, which Word reports as an unreadable file): a DOCTYPE in any part read; a header/footer part over 2 MiB, an image over 16 MiB or 32 MiB in all; any external link that is not an http, https or mailto hyperlink — an externally linked image is refused, never fetched and never copied, because Word would fetch it every time the document opens; an embedded object that is not an image; an image that is not PNG, JPEG, GIF, BMP, TIFF, EMF or WMF by both extension and leading bytes (so SVG is not carried); a field that pulls content in (INCLUDEPICTURE, INCLUDETEXT, LINK, DDE, DDEAUTO, IMPORT); a VML src / href URL. Nothing is fetched, ever. A section that is not asked for is not read, so it cannot fail a styles-only render.

Only the template's body-level (last) section is taken. Numbering inside a header (a list in the letterhead) resolves against this package's numbering.

read() reports what a header or footer holds that even the blocks form cannot (see above): a GIF logo comes back as "unrepresented": [{"where": "/page/header", "kind": "image", "count": 1}], and describe() says so. Locations and counts only, never text.

An unusable template throws TemplateException rather than falling back. A document that silently comes out in the wrong style is the failure this option exists to end — and it gives a host a way to validate a customer-supplied template at upload time rather than at render time:

Output stays deterministic: the same document and the same template always produce the same bytes.

Versions as diffs

Keep the current document as a real .docx and each older version as the ops that restore it:

The document model has no ids, so an op names the list it edits by JSON Pointer and the item by index: {"op": "blocks.replace", "path": "/blocks/4/rows/1/cells/0/blocks", "index": 0, "block": {…}}. The kinds are blocks, items, rows and cells, each with insert, remove, move and replace, plus doc.set for top-level properties and doc.replace. Agent::opSchema() has them all.

Reading Word-authored files

Agent::read() handles more than its own writer output: headings via Heading1-9 styles or outlineLvl, run formatting including named highlight colors, hyperlinks through the rels part, numPr lists with ilvl nesting (unknown numbering buckets as unordered), tables, inline images (returned as data URLs), page breaks and border-only paragraphs, and footnotes (any ids; Word's own separators skipped). Unknown constructs degrade to plain paragraphs — the reader never throws on strange XML.

Mixed pages

A pageBreak carrying page changes the page from there on. It is the same vocabulary as fine-print, and there is no other element and no sections key.

In the file each stretch is a Word section. Reading works the other way round: top-level page is the first section, and each later one a break holding only what differs from the page before it. (Before 0.20.0, page was the last section's.)

The file has read() gives
a nextPage section (the default) pageBreak with page
oddPage or evenPage pageBreak with page, and a report
continuous, same size and orientation no break, and a report
continuous, other size or orientation pageBreak with page: Word has to start a page
w:cols above 1, a page-number restart dropped, and a report
a paper size other than letter, legal or A4 dropped, and a report

A report is "unrepresented": [{"where": "/blocks/2", "kind": "layout-not-preserved", "count": 1}], at /page for the first section. Reading a section's type comes from checking files against LibreOffice; Word itself was not available to check against. A section break inside a code or quote block is not read, and reported at /page.

Reading .doc, .odt and .rtf

Agent::read() decides the format from the bytes, never the file name, and returns the same document shape for all four:

Format Comes through Does not
.docx everything above —
.doc (Word 97-2003) paragraphs, headings (by built-in style, so localised names work), direct bold / italic / underline / strike, hyperlinks, nested bulleted and numbered lists, tables with header rows, page breaks style-inherited formatting, fonts / sizes / colours, images, text boxes, headers / footers / footnotes / comments, merged cells, title
.odt headings, paragraphs, bold / italic / underline / strike, hyperlinks, nested lists, tables with header rows and merged cells, spaces / tabs / line breaks, page breaks, title images and frames, footnotes, comments, tracked deletions, fonts / sizes / colours
.rtf headings (style name or outline level), direct bold / italic / underline / strike, hyperlinks, nested lists, tables (header rows where \trhdr marks them), Unicode, \ansicpg code pages, title images and objects, footnotes, headers / footers, fonts / sizes / colours, merged cells, double-byte code pages written as raw bytes

The .doc reader is this package's own MS-CFB and MS-DOC code, with no dependency. A document converted from .docx to .doc and .odt by LibreOffice reads back identical to the .docx; the .rtf differs only in a header-row flag LibreOffice does not write (tests/fixtures/formats/).

What it cannot read it refuses with UnsupportedFormatException, whose format() names what the bytes are: doc for a Word 6/95 or encrypted file, xls, ppt, msg or cfb for another compound file, xlsx, pptx, ods, odp, or unknown. A damaged file in a supported format raises RuntimeException instead — "this file is broken" and "save it as .docx" send a person to do different things.

Word and LibreOffice templates (.dotx, .ott)

A .dotx is a .docx whose main part is declared a template; an .ott is an .odt whose mimetype (and manifest root entry) says text-template. Agent::read() reads both exactly as it reads their twins and adds "sourceKind": "template" to the result. A document read has no sourceKind key, as before.

Conversion rewrites only the declaration: the content-type value in [Content_Types].xml, or the ODF mimetype entry plus the manifest's root media-type (ODF 1.3 requires the two to match). Every other member is copied as its original zip record, byte for byte, and mimetype stays first and stored. No reader or writer is in the path.

Refused with LastWord\Exceptions\OfficeTemplateRefused (a constant reason): macro-enabled templates .dotm (macro_enabled; never read, never converted, and a .docm is not converted either), a package declaring a template of another family or whose parts disagree with its declaration (family_mismatch). The archive guards above apply first, so bombs and unsafe names raise ArchiveRefused as for any document.

Determinism

toBytes() is reproducible: no timestamps in any XML part, fixed zip entry order, and every entry's mtime pinned. The same document yields the same bytes on every call — diff-able artifacts, cache-friendly outputs.

Cross-language parity

As of 0.2.0 the metadata slots match the Node mirror exactly: the title is carried in docProps/core.xml (dc:title) and the code block language in a lastword:code:{lang} content-control tag (quotes use lastword:quote), so the same file opens in either engine — title and code language round-trip PHP ↔ Node in both directions. Files written by 0.1.x (Title-styled paragraph, LastWordCode_{lang} bookmark) still read fine; the sibling repo's canonical fixture is frozen into each test suite as a cross-read vector.

Testing

License

MIT


All versions of last-word with dependencies

PHP Build Version
Package Version
Requires php Version ^8.4
ext-zip Version *
ext-dom Version *
ext-libxml Version *
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package particle-academy/last-word contains the following files

Loading the files please wait ...