Table of Contents

Read text and walk the document

Every node in a WordDocument has GetText(), and the whole tree can be walked with a DomVisitor. Use them for search indexing, validation, or extracting data from documents.

Extract text

using DocWright;
using DocWright.Core.Document;
using DocWright.Dom;

using WordDocument document = converter.Load(File.OpenRead("table-styles.docx"));

// All text, as a reader sees it: tracked changes applied, field results not field codes.
string text = document.GetText();
Console.WriteLine(text.Split('\n')[0]);

// As it was before tracked changes.
string original = document.GetText(RevisionView.Original);

// Paragraph by paragraph, and into tables.
foreach (Section section in document.Sections)
{
    foreach (Block block in section.Blocks)
    {
        if (block is Table table)
        {
            foreach (TableRow row in table.Rows)
            {
                Console.WriteLine(string.Join(" | ", row.Cells.Select(c => c.GetText().Trim())));
            }
        }
    }
}

Output (with the counting example below)

DocWright seed document six: a table with conditional table-style formatting.
Product | Quantity | Status
Widgets | 12 | Shipped
Gadgets | 7 | Pending
Gizmos | 31 | Shipped
Sprockets | 4 | Backordered
16 paragraphs, 0 tables, 2 images

GetText() returns what a reader sees: tracked changes applied, and fields as their results rather than their codes. Pass RevisionView.Original for the text as it was before tracked changes. It works on any node: a document, section, paragraph, table cell, header or footnote.

The document tree

WordDocument
├─ Sections ─ Section
│             ├─ Blocks ─ Paragraph ─ Inlines ─ TextRun, TabChar, BreakChar, ImageRef, ShapeRef, PositionedTextBox, FieldChar, …
│             │           Table ─ Rows ─ TableRow ─ Cells ─ TableCell ─ Blocks …
│             │           SdtBlock (content control)
│             └─ (headers and footers are referenced by the section)
├─ HeaderFooters, Footnotes, Endnotes
├─ Styles, Numbering, Theme, Settings

Walk it with a visitor

Derive from DomVisitor and override the nodes you care about. Call base to keep walking into a node's children:

using DocWright.Dom;

using WordDocument letter = converter.Load(File.OpenRead("letterhead.docx"));
var counter = new ContentCounter();
letter.Accept(counter);
Console.WriteLine($"{counter.Paragraphs} paragraphs, {counter.Tables} tables, {counter.Images} images");

Then call document.Accept(visitor), as the sample does. The visitor reaches every node in document order, including table cells and content controls. A visitor that tracks context, such as "which table am I in", is shown in the JSON template tutorial.

Count words as Word does

DocumentStatistics.Compute gives the counts Word's Review > Word Count shows, by Word's rules (WQ-0107): words, characters with and without spaces, East Asian characters and paragraphs from the document, and lines and pages from its layout:

using DocWright.Core.Rendering;
using DocWright.Dom;
using DocWright.Fonts;
using DocWright.Layout;

// Words, characters and paragraphs need only the document.
DocumentStatistics quick = DocumentStatistics.Compute(document);
Console.WriteLine($"{quick.Words} words, {quick.Characters} characters ({quick.CharactersWithSpaces} with spaces), {quick.Paragraphs} paragraphs");

// Lines and pages come from a layout made with source references on.
var fonts = new FontEngine();
ResolvedDocument resolved = StyleResolver.Resolve(document, new ResolveOptions { Fonts = fonts, EmitSourceReferences = true });
LayoutDocument layout = new LayoutEngine(fonts) { EmitSourceReferences = true }.Layout(resolved);
DocumentStatistics full = DocumentStatistics.Compute(document, layout);
Console.WriteLine($"{full.Lines} lines on {full.Pages} page(s)");

Word does not split on spaces. An en or em dash separates words, a hyphen standing alone is a word, each Chinese, Japanese or Korean character is a word of its own, a footnote reference splits the word it sits in, and hidden and deleted text are left out while field results are counted:

using DocWright.Dom;
using DocWright.Dom.Editing;
using DocWright.Layout;

// Word's rules, not "split on spaces": a dash separates, a lone hyphen is a word, each CJK character is one.
using WordDocument sample = BlankDocument.Create();
Paragraph paragraph = sample.Sections[0].Blocks.OfType<Paragraph>().Single();
sample.InsertText(DocumentPosition.StartOf(paragraph), "well-known a - b one—two 日本語");
DocumentStatistics rules = DocumentStatistics.Compute(sample);
Console.WriteLine($"\"{paragraph.GetText().TrimEnd()}\": {rules.Words} words, {rules.EastAsianCharacters} East Asian characters");

Output

330 words, 1724 characters (2040 with spaces), 13 paragraphs
44 lines on 1 page(s)
"well-known a - b one—two 日本語": 9 words, 3 East Asian characters
"ll-known a -": 3 of 9 words, 0 paragraphs (the mark is not selected)

Footnotes, endnotes and text boxes are counted by default, as in Word's status bar; pass includeNotesAndTextBoxes: false for the body alone. Headers and footers are never counted.

A selection counts with Compute(document, span, layout), as Word's status bar ("12 of 345 words") and its Word Count dialog do for one: the characters the span covers, a word it cuts counted as a word, a paragraph only when the span covers its mark, the lines it touches (WQ-0115):

using DocWright.Dom;
using DocWright.Dom.Editing;
using DocWright.Layout;

// A selection, as Word's status bar counts it ("3 of 9 words"): a word the selection cuts still counts.
var selection = new DocumentSpan(DocumentPosition.InParagraph(paragraph, 2), DocumentPosition.InParagraph(paragraph, 14));
DocumentStatistics selected = DocumentStatistics.Compute(sample, selection);
Console.WriteLine($"\"{paragraph.GetText().Substring(2, 12)}\": {selected.Words} of {rules.Words} words, {selected.Paragraphs} paragraphs (the mark is not selected)");

Positioned text boxes

Most text boxes are shapes (ShapeRef) and keep their paragraphs. A floating text box DocWright can place but not model as a shape, such as one on a drawing canvas, is a PositionedTextBox: its content is a list of TextBoxSegments, text and page numbers, and a visitor reaches it through VisitPositionedTextBox. Its text is not part of GetText(); read box.Text, which gives each page number as the value the document last stored. In earlier versions such a box was an ImageRef with the content type application/vnd.docwright.textbox, and code that looked for it there finds nothing now.

Text DocWright inferred

When DocWright can't convert a drawing, it keeps the drawing's markup and adds the text inside it as ordinary runs, so that search and export see it. Those runs have IsSynthesized set, and a .docx save writes the drawing instead of them, so loading and saving a document again and again doesn't repeat the text. To make the text part of the document, set IsSynthesized to false and remove the drawing it came from (the UnknownInline right after those runs); clearing the flag alone saves both, and the next load reads the text out of the drawing again.

Other formats

To save text rather than read it in code, use the plain-text writer: converter.Save(document, stream, ".txt"). See Formats.