DOCXLibWord documents for Ring

WordReader

Read .docx files: content, styles, tables, images, layout, and rebuild a document with toWriter().

Introduction to WordReader#

WordReader (docxlib.ring) parses .docx files and provides:

  1. Structured access to the document content as Ring lists
  2. Semantic query methods — getHeadings(), getTables(), getSectionLayouts(), etc.
  3. Full round-trip — toWriter() converts the parsed document back into a WordWriter that you can modify and re-save
Ring
load "docxlib.ring"

reader = new WordReader("report.docx")
reader.loadDocx()

? reader.summary()

headings = reader.getHeadings()
for h in headings
    ? string(h[:level]) + ": " + h[:text]
next

reader.save("report_copy.docx")
reader.cleanup()

Loading and Saving#

MethodParametersDescription
new WordReader(filePath)filePath : StringConstructor — sets the source .docx path
loadDocx()—Unzip and parse the document. Call once after construction
save(outputPath)outputPath : StringRound-trip: parse → reconstruct → write
cleanup()—Delete the temporary extraction folder
toWriter()—Return a populated WordWriter from the parsed content
Note

loadDocx() resets all internal state each call, so one WordReader instance can be reused across multiple files.

Document Properties#

MethodReturnsDescription
getFilePath()StringSource file path
getTitle()StringDocument title from core.xml
getAuthor()StringDocument author
getDefaultFont()StringBody font name
getDefaultFontSize()NumberBody font size in points
getPageWidthCm()NumberPage width in cm
getPageHeightCm()NumberPage height in cm
getMarginTopCm()NumberTop margin in cm
getMarginBottomCm()NumberBottom margin in cm
getMarginLeftCm()NumberLeft margin in cm
getMarginRightCm()NumberRight margin in cm
getOrientation()String"portrait" or "landscape"
getHeaderText()StringDefault header text
getFooterText()StringDefault footer text
getEvenPageHeaderText()StringEven-page header
getEvenPageFooterText()StringEven-page footer
getFirstPageHeaderText()StringFirst-page header
getFirstPageFooterText()StringFirst-page footer
hasEvenAndOddHeaders()BoolEven/odd header mode enabled
hasFirstPageDifferent()BoolFirst-page-different mode enabled
hasPageBorder()BoolPage border present
getPageBorderStyle()StringPage border style
getPageBorderColor()StringPage border colour hex
getPageBorderSizePt()NumberPage border width in points
getPageBgColor()StringPage background colour hex
hasPageBackground()BoolSolid page background present
getColumnCount()NumberNumber of columns in the document
getColumnSpaceCm()NumberColumn gap in cm
getTOCTitle()StringTable of contents title
hasTOC()BoolTOC field present
hasWatermark()BoolText watermark present
getWatermarkText()StringWatermark text
getWatermarkOptions()ListWatermark properties
isDocumentRTL()BoolDocument-wide RTL enabled
hasPageNumbers()BoolPage number field present
getPageNumberAlign()StringPage number alignment
getCustomProperties()ListAll custom document properties
getCustomProperty(name)StringA single custom property by name

Content Query Methods#

Summary and Block Listing#

Ring
? reader.summary()        # human-readable content overview
reader.listBlocks()       # numbered block list with type + preview
blocks = reader.getBlocks()  # raw list of all parsed blocks

Paragraphs and Runs#

MethodReturnsDescription
getHeadings()List of [:level, :text, :style]All heading blocks (levels 1–6)
getParagraphs()List of paragraph blocksAll body paragraphs with formatting
getRTLParagraphs()ListRight-to-left paragraphs
getCommentedParagraphs()List of [:text, :commentText, :commentAuthor]Paragraphs with attached comments
getKeepNextParagraphs()ListParagraphs with keep-with-next set
getPageBreakBeforeParagraphs()ListParagraphs preceded by a page break
getBorderedParagraphs()ListParagraphs with a border box
getNamedStyleParagraphs(name)ListParagraphs using a specific named paragraph style
getOutlinedParagraphs()ListParagraphs with an explicit outline level
getNumberedHeadings()ListHeadings that are part of a numbered list
getTabbedParagraphs()ListParagraphs containing tab characters
getHiddenRuns()List of [:text]Runs with vanish (hidden text)
getCapsRuns()List of [:text, :type]Runs with allCaps or smallCaps
getDStrikeRuns()List of [:text]Runs with double-strikethrough
getRunBorderRuns()ListRuns with a character-level border
getRunLanguages()List of [:lang, :text]Runs with explicit language tags
getCharStyleRuns()List of [:styleName, :text]Runs referencing a named character style
getCharStyles()ListAll character style names found in the document
getTextBoxes()List of [:text]Floating text box content
MethodReturnsDescription
getListItems()List of [:text, :level, :isBullet]All list items with nesting level
getListRestartPoints()ListList items where numbering restarts
getHyperlinks()List of [:text, :url]All external hyperlinks
getCaptions()List of [:text, :label, :seqNum]SEQ figure/table captions
getBookmarks()List of [:name, :text]Named bookmark anchors

Footnotes and Endnotes#

MethodReturnsDescription
getFootnotes()List of note blocksAll footnotes
getEndnotes()List of note blocksAll endnotes

Each note block contains:

block[:id]       — note reference number
block[:refText]  — anchor text in the document body
block[:noteText] — plain concatenated note body text
block[:runs]     — list of formatted runs, each: [:text, :bold, :italic,
                    :underline, :color, :font, :size]
Ring
footnotes = reader.getFootnotes()
for fn in footnotes
    ? "Note " + fn[:id] + ": " + fn[:noteText]
    for r in fn[:runs]
        if r[:bold] = true  ? "  BOLD: " + r[:text]  ok
    next
next

Comments, Fields, Charts#

MethodReturnsDescription
getComments()List of [:id, :text, :author]All comment entries
getMergeFields()List of [:name]All MERGEFIELD entries
getMergeFieldNames()List of StringsMERGEFIELD names as a flat list
getFields()List of [:fieldType, :fieldResult]All Word fields (DATE, PAGE, TOC, SEQ, …)
getCharts()List of [:type, :title, :widthCm, :heightCm]Embedded chart metadata
getChartData()List with full series dataCharts with categories and series values

Form Fields#

MethodReturnsDescription
getFormFields()ListAll form fields (any type)
getCheckboxes()List of [:label, :checked]Checkbox controls
getDropdowns()List of [:label, :choices, :default]Dropdown controls
getTextInputs()List of [:label, :value]Text input controls

Table Query Methods#

MethodReturnsDescription
getTables()List of table blocksAll tables with full row/cell data
getTableLayouts()List of layout summariesDimension and style summary per table
getTableStyle(blockIndex)ListStyle info for a specific table
getTableRowProperties()ListRow heights and header-repeat flags
getNestedTables()ListTables nested inside cell content
getCellsWithBorders()ListCells with explicit border overrides
getCellsWithPadding()ListCells with custom padding

Table block structure:

block[:rows]        — list of rows; each row is a list of cell dicts
block[:colWidths]   — column widths in twips
block[:rowHeights]  — per-row heights in twips (0 = auto)
block[:rowHRules]   — per-row height rule strings ("atLeast" / "exact")
block[:rowIsHeader] — per-row boolean (tblHeader repeat flag)
block[:borderStyle] — table-level border style
block[:headerBg]    — header background colour hex
block[:evenRowBg]   — even-row stripe colour

Cell dict structure:

cell[:text]         — concatenated plain text
cell[:runs]         — list of runs: [:text, :bold, :italic, :color, :font,
                       :size, :lang, :styleName]
cell[:bgColor]      — background colour hex
cell[:align]        — text alignment
cell[:vAlign]       — vertical alignment
cell[:colspan]      — column span count
cell[:rowspan]      — row span count
cell[:borderStyle]  — legacy all-sides border style
cell[:borderSides]  — list of per-side entries: [:side, :style, :color, :size]
cell[:textDir]      — "btLr", "tbRl", or "" (normal)
cell[:padTop/Bottom/Left/Right] — padding in twips

Image Query Methods#

MethodReturnsDescription
getImages()List of image blocksAll inline and floating images
getImagesWithAlt()List of [:path, :altText, :widthCm, :heightCm]Images with alt text
getFloatingImages()ListFloating images with position and wrap data
getFloatingImageWrapTypes()List of [:wrapType, :wrapSide]Wrap type summary
getLandscapeSections()ListSections using landscape orientation

Image blocks include crop data when present:

block[:widthCm]   — display width in cm
block[:heightCm]  — display height in cm
block[:floating]  — true for floating images
block[:altText]   — accessibility description
block[:cropL]     — left crop in percent
block[:cropR]     — right crop in percent
block[:cropT]     — top crop in percent
block[:cropB]     — bottom crop in percent

Section and Layout Queries#

MethodReturnsDescription
getSectionLayouts()ListPer-section column, header/footer info
getSectionBreaks()ListSection break points with type and column settings
getSectionHeaders()ListSection-level header/footer text

getSectionLayouts() entry structure:

item[:breakType]     — "nextPage", "continuous", "evenPage", "oddPage"
item[:numColumns]    — column count in this section
item[:columnSpaceCm] — column gap in cm
item[:sectHeader]    — section-specific header text
item[:sectFooter]    — section-specific footer text

getSectionBreaks() entry structure:

item[:breakType]     — break type string
item[:numColumns]    — column count after the break
item[:columnSpaceCm] — column spacing in cm

Round-Trip: toWriter()#

toWriter() rebuilds the entire parsed document as a WordWriter instance. You can then add new content, modify page settings, or just call save() to produce a clean copy.

Ring
reader = new WordReader("template.docx")
reader.loadDocx()

writer = reader.toWriter()

# Append new content
writer.addPageBreak()
writer.addHeading("Appendix", 1)
writer.addParagraph("Content appended after round-trip reconstruction.", [])

writer.save("extended_output.docx")
reader.cleanup()

Round-trip fidelity table:

ElementPreserved
ParagraphsText, bold/italic/underline/strike, colour, font, size, alignment, indent, spacing
Run propertiesLanguage (:lang), character style (:charStyle), superscript/subscript
Headings 1–6Level and text
ListsBullet and numbered, nesting levels, restart points
TablesAll cells, merges, bg colours, per-side borders, row heights, text direction
ImagesInline and floating, dimensions, wrap type, alt text, crop percentages
FootnotesFull run-level formatting (bold, italic, colour, size per run)
EndnotesFull run-level formatting
HyperlinksURL and display text
BookmarksName and position
Section breaksBreak type, column count, column spacing
Page propertiesSize, margins, orientation, background, page border
Headers/FootersDefault, first-page, even-page
Paragraph controlkeepNext, keepLines, widowControl=false, noHyphenate=true
CommentsText and author
FieldsDATE, PAGE, TOC, SEQ, and other auto-updating fields
WatermarksText and image
RTLRTL paragraphs and document RTL mode

Reader Quick Reference#

Ring
load "docxlib.ring"

reader = new WordReader("doc.docx")	# load a file generated by DOCXLib 
reader.loadDocx()

# Metadata
? reader.getTitle()  ? reader.getAuthor()  ? reader.getPageWidthCm()

# Overview
? reader.summary()
reader.listBlocks()

# Content
headings   = reader.getHeadings()
tables     = reader.getTables()
images     = reader.getImages()
footnotes  = reader.getFootnotes()
charts     = reader.getCharts()
hyperlinks = reader.getHyperlinks()
listItems  = reader.getListItems()

# Run intelligence
langs    = reader.getRunLanguages()
styles   = reader.getCharStyleRuns()
hiddenTx = reader.getHiddenRuns()

# Table detail
layouts  = reader.getTableLayouts()
borders  = reader.getCellsWithBorders()
rowProps = reader.getTableRowProperties()

# Layout
sections = reader.getSectionLayouts()
breaks   = reader.getSectionBreaks()

# Form fields
boxes    = reader.getCheckboxes()
drops    = reader.getDropdowns()
inputs   = reader.getTextInputs()

# Round-trip
reader.save("output.docx")
reader.cleanup()
DOCXLib - Word documents for Ring, made with ringdoc.