cupertino-files / PagesDocument
Class: PagesDocument
Defined in: src/pages/document.ts:286
cupertino-files — read, inspect and edit Apple iWork documents (Pages, Numbers, Keynote) in pure TypeScript with zero runtime dependencies.
Layering (each importable on its own): primitives: snappy, protobuf wire (RawMessage), zip, varint, crc32 container: IWorkContainer (package layouts), IWA archives (IwaObject) graph: ObjectStore (components, IDs, references, save invariants) model: IWorkDocument + TextStorage/StylesheetModel/DrawableModel apps: PagesDocument, NumbersDocument, KeynoteDocument
Extends
Properties
container
readonlycontainer:IWorkContainer
Defined in: src/tsa/document.ts:128
Inherited from
format
readonlyformat:FormatInfo
Defined in: src/tsa/document.ts:130
Inherited from
store
readonlystore:ObjectStore
Defined in: src/tsa/document.ts:129
Inherited from
Accessors
app
Get Signature
get app():
IWorkApp
Defined in: src/tsa/document.ts:170
Returns
Inherited from
body
Get Signature
get body():
TextStorage
Defined in: src/pages/document.ts:442
The document body text storage. Throws for page-layout documents — check isPageLayout or use bodyOrUndefined when the document kind is unknown.
Returns
bodyOrUndefined
Get Signature
get bodyOrUndefined():
TextStorage|undefined
Defined in: src/pages/document.ts:431
The document body text storage, or undefined for page-layout documents (Pages' "Document Body" switch off) where text lives only in text boxes.
Returns
TextStorage | undefined
bodyText
Get Signature
get bodyText():
string
Defined in: src/pages/document.ts:465
Plain body text ("" for page-layout documents).
Returns
string
era
Get Signature
get era():
"iwork13"|"iwork16"|"iwork19"|"modern"|"current"|"future"
Defined in: src/tsa/document.ts:336
Format era this document was written by (see tsp/version.ts).
Returns
"iwork13" | "iwork16" | "iwork19" | "modern" | "current" | "future"
Inherited from
isPageLayout
Get Signature
get isPageLayout():
boolean
Defined in: src/pages/document.ts:457
True for page-layout documents: TP.SettingsArchive.body is false, or the document has no body storage at all. Word-processing documents (the default) have a body text flow; page-layout ones only have text boxes.
Returns
boolean
settings
Get Signature
get settings():
PagesSettings
Defined in: src/pages/document.ts:1075
Document-wide settings (hyphenation, ligatures, footnote config …).
Returns
stylesheet
Get Signature
get stylesheet():
StylesheetModel
Defined in: src/pages/document.ts:589
The document stylesheet (named styles live here).
Returns
Methods
addTextBox()
addTextBox(
pageIndex,text,placement?):DrawableModel
Defined in: src/pages/document.ts:1241
Put a floating text box on a page, saying text, placed and sized by placement (points; the donor's size otherwise). The box is a deep copy of a text box the document already carries — the page's first, else any page's — so it has the document's own style, its own storage and every field the app writes; a document with no text box (the blank has none) cannot grow one this way. The placement is in page points from the page's top left; a box past the page edge is listed all the same and draws only the part on the page, so size it against pageSetup().
Parameters
pageIndex
number
text
string
placement?
DrawablePlacement = {}
Returns
Agent Tool
add_text_box
allLinks()
allLinks():
object[]
Defined in: src/pages/document.ts:957
Every hyperlink in the document, including those inside text boxes.
Returns
object[]
allText()
allText():
string
Defined in: src/tsa/document.ts:279
Concatenated plain text of all in-document storages (reading order approximation).
Returns
string
Inherited from
appendParagraph()
appendParagraph(
text,style?,list?):number
Defined in: src/pages/document.ts:556
Append a paragraph to the body. style may be a style name ("Heading 1") or a style object id. Returns the new paragraph index.
list names a list style ("Bullet", "Numbered") to make the paragraph a list item; without it the paragraph is not one, whatever the paragraph before it was.
Parameters
text
string
style?
string | bigint
list?
string | bigint
Returns
number
Agent Tool
append_paragraph
appendTable()
appendTable(
rows?,name?):TableModel
Defined in: src/pages/document.ts:1397
Append a table at the end of the body, in a paragraph of its own.
Parameters
rows?
readonly readonly string[][] = []
name?
string
Returns
applyCharacterFormatting()
applyCharacterFormatting(
start,end,formatting):bigint
Defined in: src/pages/document.ts:576
Apply direct character formatting to a body range: creates an anonymous TSWP.CharacterStyleArchive (parented on the effective style at start) and spans it over [start, end). Returns the new style's id.
Parameters
start
number
end
number
formatting
Returns
bigint
Agent Tool
format_text
applyEdits()
applyEdits(
edits):void
Defined in: src/pages/document.ts:897
Apply several non-overlapping body edits from one snapshot — offsets for every edit refer to the text as it is now, in any order; an omitted replacement deletes the range. The safe way to make many changes gathered from one paragraphs()/find() pass.
Parameters
edits
readonly object[]
Returns
void
attachments()
attachments():
object[]
Defined in: src/pages/document.ts:974
Body inline attachments (page-number fields, images, footnote marks).
Returns
object[]
audit()
audit():
AuditFinding[]
Defined in: src/tsa/document.ts:242
Every fault this library knows how to recognise offline, across the whole document — the checks a person otherwise performs by opening the file in an app. Each finding names a state some review round has already watched an app refuse, repair destructively, or render against the author's intent. save() refuses the error classes it can see; audit() reports them without saving, warnings included, so a builder can ask "what would a person object to?" before shipping a document.
Returns
Agent Tool
audit_document
Inherited from
bookmarks()
bookmarks():
object[]
Defined in: src/pages/document.ts:979
Bookmarks (named destinations) declared in the body.
Returns
object[]
characterFormattingAt()
characterFormattingAt(
pos):CharacterFormatting
Defined in: src/pages/document.ts:947
Effective character formatting at a body position, inheritance folded in.
Parameters
pos
number
Returns
charts()
charts():
ChartModel[]
Defined in: src/tsa/document.ts:210
Every chart, with its plotted data (see ChartModel).
Returns
Inherited from
comments()
comments():
object[]
Defined in: src/pages/document.ts:1003
Comments anchored anywhere in the document.
Returns
object[]
compact()
compact():
number
Defined in: src/tsa/document.ts:363
Drop archives nothing can reach, returning how many went.
What this collects today is very little, and that is worth knowing before reaching for it. Removing a sheet or a table unlinks it from the document tree, but the calc engine keeps its own references to every table it ever knew, so those archives stay genuinely reachable. The gap is in removal — unregistering a table's formula owners is calc-engine surgery this library does not do yet — not in the walk. What compaction does reclaim is objects created and then abandoned, and the Data/ files (a removed picture's bytes) that no surviving object names; the count is archives and files together.
Roots are the package metadata, each component's first object, and every selection archive; see ObjectStore.prune for the scan and for why it errs towards keeping things, and ObjectStore.collectData for how a file is known to be live. It is a no-op on every untouched document in the corpus, which is the property that matters: a collector that trims a file nobody edited is broken.
Returns
number
Inherited from
compatibility()
compatibility():
CompatibilityReport
Defined in: src/tsa/document.ts:317
What this library can and cannot do with THIS document: declared versions, the era they place it in, structural probes (unknown type IDs, cell-storage generation, patch archives, collaboration state) and any unsupported features. Loading never fails on version grounds — this is how a caller finds out what to expect.
Returns
Inherited from
compatibilitySummary()
compatibilitySummary():
string
Defined in: src/tsa/document.ts:331
One-line human summary of compatibility.
Returns
string
Inherited from
IWorkDocument.compatibilitySummary
createParagraphStyle()
createParagraphStyle(
options):bigint
Defined in: src/pages/document.ts:669
Create a paragraph style and list it in the app's style panel.
Confirmed in Pages. A style created here applies as asked and appears in the paragraph styles panel. Four requirements, found one failed round in the app at a time, each necessary and none sufficient:
- a
super.name; - a
super.identifierand a matchingidentifier_to_style_mapentry — of the 146 paragraph styles in the ladder's base, the 21 that are listed all carry both; - both property bags, the field set all 3130 paragraph styles in these fixtures share;
- an entry in
TSWP.ThemePresetsArchive.paragraph_style_presets(TP.ThemeArchive.super.110.7), which in every fixture holds exactly the names the app shows and whose length tracks what the user sees — twelve in a stock document, 35 and 61 in the two imported from Word.
The first three produce a style that renders correctly and whose name Pages prefills when adding a style by hand — and still does not list. unlistParagraphStyle was built as the control (removal proves which list the panel reads in a way addition cannot), and listedParagraphStyles reads the panel's own order back.
copyOf starts the new style's property bags as a full copy of an existing style's — the dense shape every listed corpus style has. Whether density is also required went unrecorded in the confirming report, so sparse styles list on faith; dense ones on evidence.
Parameters
options
basedOn?
string | bigint
character?
copyOf?
string | bigint
name
string
paragraph?
Returns
bigint
defineAsPlaceholder()
defineAsPlaceholder(
start,end):bigint
Defined in: src/pages/document.ts:942
Mark a body span as placeholder text, the way Format → Advanced → Define as Placeholder Text does. Returns the field's id.
Parameters
start
number
end
number
Returns
bigint
deleteRange()
deleteRange(
start,end):void
Defined in: src/pages/document.ts:543
Parameters
start
number
end
number
Returns
void
drawables()
drawables():
DrawableModel[]
Defined in: src/tsa/document.ts:195
Every object that carries drawable geometry (shapes, images, boxes).
Returns
Inherited from
fillPlaceholder()
fillPlaceholder(
placeholder,text):TextRange
Defined in: src/pages/document.ts:918
Fill a body placeholder: real text in, placeholder marking off, styling kept — what typing into one does in Pages. Returns the filled span as a fluent range.
A number indexes the listing as of this call: a fill removes its entry, so the indexes of the placeholders after it shift down by one — filling 0, 1, 2 from one remembered listing lands two of them in the wrong fields. To fill several, pass the entries of one placeholders snapshot (each carries the fieldId that pins it, resolved live at the fill), or pass field ids directly.
Parameters
placeholder
number | bigint | { end: number; fieldId?: bigint; start: number; }
text
string
Returns
find()
find(
pattern):TextRange[]
Defined in: src/pages/document.ts:882
Find body-text matches as fluent ranges.
Parameters
pattern
string | RegExp
Returns
floatingDrawablePages()
floatingDrawablePages():
number[]
Defined in: src/pages/document.ts:1306
Page indexes that currently hold floating drawables.
Returns
number[]
floatingDrawables()
floatingDrawables(
pageIndex?,options?):DrawableContainer|undefined
Defined in: src/pages/document.ts:1250
Parameters
pageIndex?
number
options?
create?
boolean
Returns
DrawableContainer | undefined
footnotes()
footnotes():
object[]
Defined in: src/pages/document.ts:998
Footnotes/endnotes anchored in the body (edit via .storage).
Returns
object[]
images()
images():
ImageModel[]
Defined in: src/tsa/document.ts:215
Every image, with filter/mask access (see ImageModel).
Returns
Inherited from
insertInlineImage()
insertInlineImage(
pos,data,options):object
Defined in: src/pages/document.ts:1332
Insert an image inline at a body-text position. Registers the bytes as a Data/ file (SHA-1 deduped), creates the TSD.ImageArchive + attachment objects, anchors them at a U+FFFC character, and sizes the image from its intrinsic dimensions — PNG/JPEG/GIF pixels, or a PDF's first-page MediaBox in points — scaled to fit maxWidth (default 400 pt) unless explicit width/height are given. A PDF is media like any raster image: the corpus's PDF figures use the same archive, and stay vector when the app scales them. App-confirmed: ladder rung P11 renders at the size asked.
The image rides the text: it sits in the text column and moves with the paragraph's indent, because the drawable carries the in-the-text-flow exterior_text_wrap. Pass wrap: "page" for the other behaviour, where the image is placed against the page margins and text flows around it — with an indented body that means the picture will not line up with the words above it.
Parameters
pos
number
data
Uint8Array
options
fileName
string
height?
number
maxWidth?
number
width?
number
wrap?
"text" | "page"
Returns
object
dataId
dataId:
bigint
imageId
imageId:
bigint
Agent Tool
add_image
insertInlineTable()
insertInlineTable(
pos,options?):TableModel
Defined in: src/pages/document.ts:1426
Insert a table inline at a body-text position: the neutral table every app shares — the blank Numbers document's own, Apple-made — grafted in, or with copyOf a copy of a table already in the document.
Copy-based like NumbersDocument.addTable, because a table's object graph — model, data store, tiles, data lists, per-band styles — is far beyond what can be invented safely; every identity in the copy comes from an Apple-authored source. rows fits and fills the table. A copy forks its data lists (the clone walk follows the whole table subtree), so filling it never touches the source — the save-time integrity gate would refuse the file if it did.
The anchoring is the measured inline-table shape: the info's parent is the body storage, its geometry sits at the origin with the standard flags, and a five-field attachment ties it to a U+FFFC character.
Parameters
pos
number
options?
copyOf?
bigint
name?
string
rows?
readonly readonly string[][]
withContent?
boolean
Returns
Agent Tool
add_table
insertLink()
insertLink(
start,end,url,options?):bigint
Defined in: src/pages/document.ts:988
Make a body range a hyperlink.
Parameters
start
number
end
number
url
string
options?
characterStyle?
string | bigint | false
Returns
bigint
Agent Tool
insert_link
insertPageBreak()
insertPageBreak(
paragraphIndex):void
Defined in: src/pages/document.ts:1115
End a paragraph with a page break, so the next one starts a new page: the paragraph's terminator becomes U+0005, which is what Insert ▸ Page Break writes and what every one of the corpus's page-break characters is, a terminator in place of the U+000A. Same length, so every attribute table keeps its indexes.
Parameters
paragraphIndex
number
Returns
void
insertSectionBreak()
insertSectionBreak(
paragraphIndex,options?):PagesSection
Defined in: src/pages/document.ts:1125
Parameters
paragraphIndex
number
options?
name?
string
pageNumberStart?
number
Returns
insertText()
insertText(
pos,text):void
Defined in: src/pages/document.ts:539
Parameters
pos
number
text
string
Returns
void
links()
links():
object[]
Defined in: src/pages/document.ts:952
Body hyperlinks ([] for page-layout documents).
Returns
object[]
listedParagraphStyles()
listedParagraphStyles():
StyleInfo[]
Defined in: src/pages/document.ts:689
The paragraph styles the app lists in its style panel, in panel order.
Distinct from paragraphStyles, which is every style the stylesheet chain holds — 146 of them in the ladder's base document against the twelve the panel shows. The rest are overrides and variations the app deliberately hides.
Returns
listInThemeStyles()
listInThemeStyles(
styleId):void
Defined in: src/pages/document.ts:763
Append a style to the theme's panel list, in the preset list its type belongs to: TSWP.ThemePresetsArchive carries three — paragraph, character and list style presets — and the app refuses a document whose paragraph list holds a character style. A style of any other type throws.
Parameters
styleId
bigint
Returns
void
listStyles()
listStyles():
StyleInfo[]
Defined in: src/pages/document.ts:1018
Named list styles available to this document.
Returns
object()
object(
id):IwaObject|undefined
Defined in: src/tsa/document.ts:286
Parameters
id
bigint
Returns
IwaObject | undefined
Inherited from
pageSetup()
pageSetup():
PageSetup
Defined in: src/pages/document.ts:832
Returns
paragraph()
paragraph(
index):ParagraphHandle
Defined in: src/pages/document.ts:887
Fluent handle for one body paragraph.
Parameters
index
number
Returns
paragraphs()
paragraphs():
ParagraphInfo&object[]
Defined in: src/pages/document.ts:517
Body paragraphs with resolved style names ([] for page-layout documents).
Returns
ParagraphInfo & object[]
paragraphStyles()
paragraphStyles():
StyleInfo[]
Defined in: src/pages/document.ts:597
Named paragraph styles available to this document.
Returns
paragraphStylesInUse()
paragraphStylesInUse():
object[]
Defined in: src/pages/document.ts:626
Which paragraph styles the body actually uses, most-used first — as against paragraphStyles, which is everything the template defines. A template usually defines styles its own sample content never demonstrates, and those are the ones whose look nobody has seen next to the rest.
Returns
object[]
placeholders()
placeholders():
object[]
Defined in: src/pages/document.ts:902
The body's placeholder-text spans ("tap or click to add …").
Returns
object[]
pruneRoots()
protectedpruneRoots():bigint[]
Defined in: src/tsa/document.ts:375
Objects that must survive compact.
The package metadata anchors the component and data tables, and each component's first object anchors that component — a component whose objects all vanished would still be listed in the metadata, which is a worse state than a few extra archives.
Returns
bigint[]
Inherited from
range()
range(
start,end):TextRange
Defined in: src/pages/document.ts:877
Fluent range over body text.
Parameters
start
number
end
number
Returns
replaceText()
replaceText(
find,replace):number
Defined in: src/pages/document.ts:535
Literal find/replace across the body, preserving the styling of the surrounding text. Returns how many occurrences changed.
Parameters
find
string
replace
string
Returns
number
Agent Tool
replace_text
save()
save():
Uint8Array
Defined in: src/tsa/document.ts:394
Returns
Uint8Array
Inherited from
sections()
sections():
PagesSection[]
Defined in: src/pages/document.ts:803
Sections of the document, from the body storage's section table. Every document has at least one.
Returns
setListStyle()
setListStyle(
paragraphIndex,style):void
Defined in: src/pages/document.ts:1010
Apply a list style ("Bullet", "Numbered", "None", …) to a paragraph.
Parameters
paragraphIndex
number
style
string | bigint
Returns
void
setPageSetup()
setPageSetup(
update):void
Defined in: src/pages/document.ts:853
Update page geometry (points; 1 pt = 1/72 in). Only given fields change.
Parameters
update
Partial<PageSetup>
Returns
void
Agent Tool
set_page_setup
setParagraphStyle()
setParagraphStyle(
paragraphIndex,style):void
Defined in: src/pages/document.ts:565
Set a paragraph's style by name or id.
Parameters
paragraphIndex
number
style
string | bigint
Returns
void
smartFields()
smartFields():
object[]
Defined in: src/pages/document.ts:969
Body smart fields — page numbers, dates, merge fields, links, …
Returns
object[]
stats()
stats():
DocumentStats
Defined in: src/tsa/document.ts:294
Returns
Inherited from
stylesheets()
stylesheets():
StylesheetModel[]
Defined in: src/tsa/document.ts:186
All stylesheets (document + theme).
Returns
Inherited from
tables()
tables():
TableModel[]
Defined in: src/pages/document.ts:1044
Tables in document order: the body's anchored tables first, by their position in the text, then floating tables in paint order, then any the anchors do not reach (storage order). tables()[0] is the first table in the document whatever was added this session.
Returns
Overrides
textBoxes()
textBoxes():
object[]
Defined in: src/pages/document.ts:1083
Text boxes and shapes carrying text: drawable + its text storage.
Returns
object[]
textStorages()
textStorages(
kind?):TextStorage[]
Defined in: src/tsa/document.ts:175
Every text storage in the document (bodies, headers, cells, notes …).
Parameters
kind?
number
Returns
Inherited from
toMarkdown()
toMarkdown(
options?):string
Defined in: src/pages/document.ts:477
The document as Markdown: the first section's header and footer as front matter, then the body with its inline tables and pictures where they are anchored, the text of the shapes and text boxes placed on the pages (all the text of a page-layout document), then every other table under its name, the floating pictures, then the charts.
Parameters
options?
MarkdownOptions = {}
Returns
string
Overrides
typeNameOf()
typeNameOf(
obj):string|undefined
Defined in: src/tsa/document.ts:290
Parameters
obj
Returns
string | undefined
Inherited from
unlistParagraphStyle()
unlistParagraphStyle(
id):boolean
Defined in: src/pages/document.ts:710
Take a paragraph style out of the panel list, leaving the style itself in place and still applied wherever it is used.
Returns whether it was listed. The inverse of what createParagraphStyle does, and the control for it: adding an entry and seeing nothing appear says only that the addition did not work, while removing an entry and seeing an entry vanish says the list is the thing the panel reads.
Parameters
id
bigint
Returns
boolean
blank()
staticblank():PagesDocument
Defined in: src/pages/document.ts:421
A new, empty Pages document — A4, vanilla styling, no template file needed.
The embedded donor is an Apple-written corpus fixture emptied by blankFrom and re-papered to A4 with byte-measured values, so every style and identity in the "new" document was authored by an Apple app. scripts/make-blanks.ts records its provenance.
Returns
PagesDocument
Agent Tool
create_document
blankFrom()
staticblankFrom(template):PagesDocument
Defined in: src/pages/document.ts:317
A new, empty document built from one you supply.
There is no from-nothing constructor, and there will not be one. A Pages document is dozens of interlinked archives — theme, stylesheet, section templates, master drawables — and inventing that graph would produce a file nothing offline could validate. Emptying a real one is safe: every identity, style and master stays exactly as an Apple app wrote it, and only the content goes.
The body text is cleared and the first paragraph's style is kept, so the result is a blank page in the template's design. Headers, footers and masters are left alone — they are the template.
Parameters
template
Uint8Array
Returns
PagesDocument
fromMarkdown()
staticfromMarkdown(markdown,options?):PagesDocument
Defined in: src/pages/document.ts:348
A new document written from Markdown: headings become the template's Title, Heading, Heading 2 and Heading 3 paragraphs (deeper levels share Heading 3), paragraphs Body, bullet and numbered lists Body items with the Bullet or Numbered list style, block quotes Body paragraphs, each pipe table an inline table in a paragraph of its own, and each image on a line of its own an inline picture, when images supplies its bytes by the source the Markdown names. Links become hyperlinks and footnote references with a definition become footnotes, and bold and italic direct formatting. A front matter block at the top is left out of the body; its header and footer are written where the document has a section to carry them, which a template has and the blank document has not. With template, the document is that one emptied (blankFrom) and the style names are looked up in it, so a letterhead's own Title, Heading and Body apply; a name the template lacks leaves the paragraph in its default style.
Parameters
markdown
string
options?
images?
ImageResolver
template?
Uint8Array<ArrayBufferLike>
Returns
PagesDocument
Agent Tool
create_document
load()
staticload(bytes):PagesDocument
Defined in: src/pages/document.ts:294
Parameters
bytes
Uint8Array
Returns
PagesDocument
loadStore()
protectedstaticloadStore(bytes,app,extractors):object
Defined in: src/tsa/document.ts:155
Parameters
bytes
Uint8Array
app
extractors
ReadonlyMap<number, ReferenceExtractor>
Returns
object
container
container:
IWorkContainer
store
store:
ObjectStore
Inherited from
open()
staticopen(bytes):IWorkDocument
Defined in: src/tsa/document.ts:142
Load any modern iWork document, auto-detecting the app. Prefer the app subclasses' load when the type is known — they expose richer APIs.
Parameters
bytes
Uint8Array