Working with Documents
Working with Documents
Aspose.Words FOSS for .NET represents every Word file as an in-memory object model rooted at the Document class, with DocumentBuilder providing a high-level, cursor-based API for authoring content. This guide covers creating and loading documents, authoring with DocumentBuilder, the section/body structure, walking the node tree, combining documents, and protecting them.
Creating and Loading Documents
Create a blank document with new Document(), or open an existing file by passing a path or Stream to the Document(fileName) or Document(stream) constructor. Overloads that accept a LoadOptions argument let you control loading behavior, such as supplying a password for an encrypted file.
Before loading a file from an unknown or untrusted source, FileFormatUtil.DetectFileFormat(fileName) (or the Stream overload) returns a FileFormatInfo describing the detected LoadFormat, and whether the file IsEncrypted, HasDigitalSignature, or HasMacros.
Authoring with DocumentBuilder
DocumentBuilder wraps a Document and exposes a cursor that you move through the document while inserting content. Write(text) and Writeln(text) insert text at the cursor; InsertParagraph() starts a new paragraph. Formatting properties on the builder — Font, ParagraphFormat, ListFormat, PageSetup — apply to whatever is written next.
Move the cursor with MoveToDocumentStart(), MoveToDocumentEnd(), MoveToSection(sectionIndex), MoveToBookmark(bookmarkName), or MoveToParagraph(paragraphIndex, characterIndex). The builder’s CurrentNode, CurrentParagraph, and CurrentSection properties report its current position in the tree.
Document Structure: Sections and Body
A Document holds a SectionCollection (Document.Sections, plus FirstSection / LastSection); each Section has one Body, an optional headers/footers collection, and its own PageSetup. Section.AppendContent(sourceSection) and PrependContent(sourceSection) copy content between sections, and ClearContent() resets a section without removing it from the document.
Within a Body, content is exposed through Body.Paragraphs (a ParagraphCollection) and Body.Tables. A Range — available from Document, Section, Paragraph, and other nodes — represents a contiguous area of the tree; Range.Text reads its plain text and Range.Replace(pattern, replacement) performs a find-and-replace over just that area.
Walking the Node Tree with DocumentVisitor
Every part of a document — sections, paragraphs, runs, tables, fields, shapes, comments, footnotes — is a Node in a composite tree rooted at Document. To process every node of a given type without manually recursing, subclass the abstract DocumentVisitor and override the Visit*Start / Visit*End callbacks you need, such as VisitParagraphStart(paragraph) or VisitRun(run), then call document.Accept(visitor). Each callback can return a VisitorAction (Continue, SkipThisNode, or Stop) to control how the traversal proceeds.
Cloning, Importing, and Appending Content
Document.Clone() produces a deep copy of an entire document. To move content between two different Document instances, call ImportNode(srcNode, isImportChildren) on the destination document to bring in a node from a foreign tree, or call Document.AppendDocument(srcDoc, importFormatMode) to append one document’s sections onto another using a chosen ImportFormatMode — KeepSourceFormatting, UseDestinationStyles, or KeepDifferentStyles. DocumentBuilder.InsertDocument(srcDoc, importFormatMode) inserts a source document’s content at the builder’s cursor instead of at the end of the destination.
Protecting Documents
Document.Protect(type, password) restricts editing according to a ProtectionType value — ReadOnly, AllowOnlyComments, AllowOnlyRevisions, AllowOnlyFormFields, or NoProtection to remove protection. Unprotect() (with or without a password) reverses it. This is an editing restriction enforced by Word, separate from the OOXML password encryption that OoxmlSaveOptions.Password applies when saving a file.
Tips and Best Practices
- Prefer
DocumentBuilderfor constructing new content; drop to direct node manipulation (AppendChild,InsertAfter,Clone) when you need fine control over an existing tree. - Call
FileFormatUtil.DetectFileFormatbefore loading a file from an untrusted or user-supplied source so you can checkLoadFormatand reject unsupported or encrypted input early. - When combining documents with
AppendDocumentorInsertDocument, choose theImportFormatModedeliberately —KeepSourceFormattingpreserves the source’s look,UseDestinationStylesmatches the target document’s style set. - Use a
DocumentVisitorsubclass instead of manual recursive tree-walking when you need to process every instance of a node type consistently. Document.Protectis an editing restriction, not encryption — pair it withOoxmlSaveOptions.Passwordif the saved file itself must require a password to open.
Common Issues
| Issue | Cause | Fix |
|---|---|---|
Document(fileName) throws for a file that opens fine in Word | The file’s format isn’t one this edition supports for loading | Call FileFormatUtil.DetectFileFormat first and check the returned LoadFormat before loading |
| Appended content picks up the wrong fonts or styles | ImportFormatMode mismatch between the source and destination style sets | Pass KeepSourceFormatting or UseDestinationStyles explicitly instead of relying on a default |
DocumentVisitor traversal stops early or skips content | A Visit*Start / Visit*End override returns SkipThisNode or Stop unintentionally | Return VisitorAction.Continue from every override unless you specifically intend to skip or stop |
Unprotect() has no effect | The document wasn’t protected with a password, or the wrong password was supplied | Call Unprotect() with no arguments if Protect was called without a password, otherwise pass the matching password |
FAQ
What’s the difference between Document.Clone() and ImportNode?
Clone() copies an entire document into a new Document instance. ImportNode(srcNode, isImportChildren) brings a single node (and optionally its children) from one document’s tree into another, which is what you use when combining specific content rather than whole documents.
Which file formats can Document(fileName) load?
Document(fileName) loads DOCX, DOCM, DOTX, DOTM, Flat OPC (plus its macro-enabled and template variants), Markdown, and plain text. Older word-processing and web formats are excluded from this edition’s loaders.
How do I find where a DocumentBuilder is currently positioned?
Read CurrentNode, CurrentParagraph, or CurrentSection on the builder instance.
Does Document.Protect encrypt the saved file?
No — it’s an editing restriction enforced by Word when the file is opened. To require a password just to open the file, set OoxmlSaveOptions.Password when saving.
How do I read just the paragraphs in a document’s body?
Use the Body.Paragraphs collection, or Body.GetChildNodes(nodeType, isDeep) for other node types.
API Reference Summary
| Class/Method | Description |
|---|---|
Document | Root of the document object model; constructors load from a file or stream, or create a blank document. |
Document.Save | Writes the document to a file, stream, or HTTP response in a chosen format. |
Document.Clone() | Produces a deep copy of the entire document. |
Document.Protect(type, password) / Unprotect() | Applies or removes an editing restriction. |
Document.AppendDocument(srcDoc, importFormatMode) | Appends another document’s sections to this one. |
DocumentBuilder | Cursor-based API for writing text and inserting content into a document. |
DocumentBuilder.InsertDocument(srcDoc, importFormatMode) | Inserts a source document’s content at the cursor. |
Section / SectionCollection | A single section of a document, and the collection of all sections. |
Body | Container for the main text (paragraphs and tables) of a section. |
Range | A contiguous area of the document tree; supports Text and Replace. |
DocumentVisitor | Abstract base class for walking every node in the document tree. |
ProtectionType | Enum of document-level editing restrictions. |
FileFormatUtil.DetectFileFormat | Detects the format of a file or stream before loading it. |