Skip to content
Extracting Content

Extracting Content

Reading a document splits into its text and its metadata, and the two use different APIs.

Document.ExtractText walks the body and returns a DocText, whose Items are one TextItem per run. Each item keeps pointers back to the paragraph, run, hyperlink, table cell and drawing it came from, so you can search for text and still know how it was formatted and where it sat. Flattening that to a string is a second decision: Text() puts every run on its own line, which splits a sentence wherever the formatting changes, while TextWithOptions joins runs within a paragraph and breaks at paragraph boundaries instead.

The other thing to decide early is whether you want list numbering included. A bulleted or numbered paragraph does not store its marker as text, because Word generates it from the numbering definition, so plain extraction returns the item content without the number in front of it. Reconstructing the numbers is an option on TextWithOptions, and a separate guide, because the reconstruction has its own set of cases it does not handle.

What extraction reaches is narrower than it first looks. The body, its tables and its text boxes are covered. Headers and footers are separate parts and need ExtractFromHeader and ExtractFromFooter. Footnotes, endnotes, and text inside tracked changes that have not been accepted or rejected have no route out at all.

Properties are two sets, not one. The built-in set covers title, author, category and the rest of the fields Word shows in its document information panel; it lives in docProps/core.xml and is reached through Document.CoreProperties. Custom properties are arbitrary name and value pairs an author or a program adds, they live in docProps/custom.xml, a part many documents do not have at all, and they are read and written through GetOrCreateCustomProperties with one typed setter per value type. Both fields come from common.DocBase, so the same calls work on a spreadsheet and a presentation.

Where to look

GuideCovers
Extract Text from a DocumentPulling the body text out of a document, with run formatting and table position.
Extract Text with List NumberingIncluding generated list markers in the output.
Document PropertiesReading and changing the built-in properties.
Custom PropertiesArbitrary name and value pairs.
Last updated on