Skip to main content
You are viewing help content for pre-release software. This document and the features it describes are subject to change.
All docs
V26.2
  • Extract Content

    • 15 minutes to read

    The Word Processing Document API allows you to read content from Word documents. You can extract text from an entire document or from individual document elements, read hyperlink targets and field codes, save document images to files, and copy document content to another document.

    A document stores content in multiple containers (the document body, headers, footers, comments, and shape text boxes). Each container contains blocks (paragraphs and tables). Paragraphs contain inline elements (text fragments, fields, hyperlinks, and shapes).

    Refer to the following help topic for additional information: Manage Paragraphs.

    Extract All Document Text

    To extract the text of the document body, call the WordDocument.Save(stream, documentFormat) method and set the documentFormat parameter to DocumentFormat.PlainText. The plain text contains paragraph text, table cell text, list item numbers and bullets, and field results.

    The following code snippet saves the text of Document.docx to a TXT file:

    using System.IO;
    using DevExpress.Docs.Word;
    
    using var inputStream = File.OpenRead("Document.docx");
    using var document = new WordDocument(inputStream);
    
    Directory.CreateDirectory("output");
    using var outputStream = File.Create(Path.Combine("output", "Document.txt"));
    document.Save(outputStream, DocumentFormat.PlainText);
    

    Note

    Plain text does not include headers, footers, comments, and text box content. The Extract Text from Headers, Footers, Comments, and Text Boxes section describes how to extract this content.

    To get the document body text as a string, call the DocumentFragment.GetText() method for the WordDocument.Body object. The returned text also includes field codes and placeholder characters for shapes.

    Compare Text Extraction Methods

    The API includes three ways to extract text. Choose a way based on the content that you need:

    Content Save method with DocumentFormat.PlainText DocumentFragment.GetText methods GetText methods of document elements
    Paragraph mark \r\n \r\n \r\n
    Line break \r\n \v \v
    List item numbers and bullets Included Included Not included
    Fields Field results Field codes, field results, and field characters Field results
    Hyperlinks Display text Field codes and display text Display text
    Shapes Not included A placeholder character (U+0008) Not included

    Extract Text from Paragraphs and Tables

    The WordDocument.Body property gets a DocumentFragment object that contains paragraphs and tables in document order. Table cells contain paragraphs and nested tables (TableCell.Content).

    Call the following methods to extract text from individual document elements:

    Method Description
    Paragraph.GetText() Returns the paragraph text.
    Table.GetText() Returns the text of all cells in the table.
    TableRow.GetText() Returns the text of all cells in the row.
    TableCell.GetText() Returns the cell text.
    Hyperlink.GetText() Returns the hyperlink text.
    Field.GetText() Returns the field result text.
    FieldFragment.GetText() Returns the text of the field code or field result.

    The returned text contains a paragraph mark (\r\n) at the end of each paragraph, including the last paragraph. Table, row, and cell text contains the text of each cell paragraph. Call the String.TrimEnd method to remove the final paragraph mark.

    The following code snippet writes the text of document body paragraphs and table rows to the console:

    using System;
    using System.IO;
    using System.Linq;
    using DevExpress.Docs.Word;
    
    using var stream = File.OpenRead("Document.docx");
    using var document = new WordDocument(stream);
    
    foreach (var block in document.Body) {
        if (block is Paragraph paragraph) {
            Console.WriteLine(paragraph.GetText().TrimEnd());
        }
        else if (block is Table table) {
            // Write each table row as a line with tab-separated cell text.
            foreach (var row in table.Rows)
                Console.WriteLine(string.Join("\t", row.Cells.Select(cell => cell.GetText().TrimEnd())));
        }
    }
    

    Refer to the following help topics for additional information:

    Extract Text from a Document Range

    To extract text from a part of a document, pass a DocumentRange object to the DocumentFragment.GetText(range) method. Use one of the following members to get a range:

    The GetText(range) method returns text in the same format as the DocumentFragment.GetText() method.

    The following code snippet writes the text of the ExecutiveSummary bookmark to the console:

    using System;
    using System.IO;
    using DevExpress.Docs.Word;
    
    using var stream = File.OpenRead("Document.docx");
    using var document = new WordDocument(stream);
    
    var bookmark = document.Bookmarks["ExecutiveSummary"];
    Console.WriteLine(bookmark.DocumentFragment.GetText(bookmark.Range));
    

    Refer to the following help topic for additional information: Manage Text and Breaks.

    Hyperlinks and fields are inline elements in the Paragraph.InlineElements collection. Check the type of each inline element to find hyperlinks and fields.

    A Hyperlink object contains the following data:

    A Field object contains a field code and a field result. Use Field.Code and Field.Result properties to access the field code and result. Call the FieldFragment.GetText() method to get field code or result text. For example, the field code text of a page number field contains PAGE.

    The following code snippet writes the display text and target of each hyperlink in the document body and table cells to the console:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using DevExpress.Docs.Word;
    
    using var stream = File.OpenRead("Document.docx");
    using var document = new WordDocument(stream);
    
    foreach (var paragraph in GetParagraphs(document.Body)) {
        foreach (var hyperlink in paragraph.InlineElements.OfType<Hyperlink>()) {
            var target = string.IsNullOrEmpty(hyperlink.Uri) ? $"#{hyperlink.Anchor}" : hyperlink.Uri;
            Console.WriteLine($"{hyperlink.GetText()}: {target}");
        }
    }
    
    // Get paragraphs from the specified blocks and table cells.
    static IEnumerable<Paragraph> GetParagraphs(IEnumerable<Block> blocks) {
        foreach (var block in blocks) {
            if (block is Paragraph paragraph) {
                yield return paragraph;
            }
            else if (block is Table table) {
                foreach (var row in table.Rows)
                    foreach (var cell in row.Cells)
                        foreach (var cellParagraph in GetParagraphs(cell.Content))
                            yield return cellParagraph;
            }
        }
    }
    

    Refer to the following help topics for additional information:

    Extract Text from Headers, Footers, Comments, and Text Boxes

    Document body text does not include headers, footers, comments, or text box content. Use the following members to extract this content:

    Content Members
    Headers and footers Section.Headers and Section.Footers collections contain headers and footers of a section. Call the SectionHeaderFooterBase.GetText() method to get header or footer text.
    Comments and replies The WordDocument.Comments collection contains document comments. Call the CommentBase.GetText() method to get comment text and the CommentBase.GetCommentedText() method to get the commented document text.
    Shape text boxes The Shape.Content property gets a ShapeTextBoxContent object (a DocumentFragment descendant). Call the DocumentFragment.GetText() method to get text box text.

    These methods return text in the same format as the DocumentFragment.GetText() method. For example, footer text includes field codes of page number fields.

    The following code snippet outputs the author, date, commented text, and text of each comment and reply to the console:

    using System;
    using System.IO;
    using DevExpress.Docs.Word;
    
    using var document = new WordDocument(File.ReadAllBytes("Document.docx"));
    foreach (var comment in document.Comments)
    {
        Console.WriteLine($"{comment.Author} ({comment.Date:g}) on \"{comment.GetCommentedText()}\": {comment.GetText()}");
        foreach (var reply in comment.Replies)
            Console.WriteLine($"    {reply.Author} ({reply.Date:g}): {reply.GetText()}");
    }
    

    Refer to the following help topics for additional information:

    Extract Images

    A PictureShape object is a picture in a document. Pictures are inline elements in the Paragraph.InlineElements collection. The PictureShape.Image property gets the picture image:

    • If the document stores the image, the Image property gets an OfficeImage object. Use the OfficeImage.DXImage property to access the image and call the DXImage.Save method to save the image in the specified format (DXImageFormat).
    • If the picture refers to an external image file, the Image property gets a UriOfficeImage object. The UriOfficeImage.Uri property gets the image file location.

    A paragraph can also contain shape groups (GroupShape) and drawing canvases (CanvasShape). The ContainerShapeBase.Shapes collection contains child shapes of a group or canvas, including pictures and nested groups. The Paragraph.InlineElements collection does not include these child shapes. To find all pictures, check the child shapes of each group and canvas.

    The following code snippet saves pictures from the document body, table cells, shape groups, and drawing canvases to PNG files:

    using System.Collections.Generic;
    using System.IO;
    using DevExpress.Docs;
    using DevExpress.Docs.Word;
    using DevExpress.Drawing;
    
    using var stream = File.OpenRead("Document.docx");
    using var document = new WordDocument(stream);
    Directory.CreateDirectory("output");
    
    var imageIndex = 0;
    foreach (var paragraph in GetParagraphs(document.Body)) {
        foreach (var picture in GetPictures(paragraph.InlineElements)) {
            // Skip pictures linked to external image files.
            if (picture.Image is OfficeImage image) {
                imageIndex++;
                image.DXImage.Save(Path.Combine("output", $"Image{imageIndex}.png"), DXImageFormat.Png);
            }
        }
    }
    
    // Get paragraphs from the specified blocks and table cells.
    static IEnumerable<Paragraph> GetParagraphs(IEnumerable<Block> blocks) {
        foreach (var block in blocks) {
            if (block is Paragraph paragraph) {
                yield return paragraph;
            }
            else if (block is Table table) {
                foreach (var row in table.Rows)
                    foreach (var cell in row.Cells)
                        foreach (var cellParagraph in GetParagraphs(cell.Content))
                            yield return cellParagraph;
            }
        }
    }
    
    // Get pictures from the specified inline elements, shape groups, and drawing canvases.
    static IEnumerable<PictureShape> GetPictures(IEnumerable<Inline> elements) {
        foreach (var element in elements) {
            if (element is PictureShape picture) {
                yield return picture;
            }
            else if (element is ContainerShapeBase container) {
                foreach (var childPicture in GetPictures(container.Shapes))
                    yield return childPicture;
            }
        }
    }
    

    Note

    Headers, footers, comments, and shape text boxes can also contain pictures. To extract pictures from these containers, pass the container content to the GetParagraphs method in the code snippet.

    Copy Content to Another Document

    To extract a part of a document with formatting settings, copy the content to another document. You can copy content in two ways:

    Insert a copy of a document range Add document elements
    Copied content Content in the specified range (for example, a part of a paragraph) Entire paragraphs, tables, and inline elements
    Bookmarks, comments, and range permissions The copy contains items that the source range fully covers Not copied
    Styles The InsertOptions value specifies how to apply source styles and formatting settings Elements keep style names and use styles of the target document
    Source document Not modified Shares added elements with the target document (unless you add copies)

    Insert a Copy of a Document Range

    Get the range of the content and pass the range to the DocumentFragment.InsertDocumentContent(position, source, options) method. The InsertOptions value specifies how to apply source styles and formatting settings. The InsertDocumentContent method inserts a copy of the content and does not modify the source document.

    The following code snippet copies a table from Document.docx to a new document, keeps the source table formatting, and saves the new document to a DOCX file:

    using System.IO;
    using System.Linq;
    using DevExpress.Docs.Word;
    
    using var inputStream = File.OpenRead("Document.docx");
    using var source = new WordDocument(inputStream);
    var budgetTable = source.Body.OfType<Table>().First();
    var sourceRange = source.Body.GetRange(budgetTable);
    
    using var document = new WordDocument();
    document.Body.AddParagraph("Budget Summary");
    var note = document.Body.AddParagraph("Source: Project Phoenix Status Report.");
    
    // Insert a copy of the table before the second paragraph.
    var position = document.Body.GetRange(note).Start;
    document.Body.InsertDocumentContent(position, sourceRange, InsertOptions.KeepSourceFormatting);
    
    Directory.CreateDirectory("output");
    using var outputStream = File.Create(Path.Combine("output", "Document.docx"));
    document.Save(outputStream, DocumentFormat.Docx);
    

    Add Document Elements to Another Document

    You can add paragraphs, tables, and inline elements (for example, text fragments) from one document to another document. Call the DocumentFragment.Add(block) or DocumentFragment.Insert(index, block) method to add a paragraph or table. To add an inline element to a paragraph, call the Add or Insert method of the Paragraph.InlineElements collection.

    The API does not copy an added element. Both documents contain the same object, and element modifications apply to both documents. To add an independent copy, call the OfficeObject.Clone() method and add the returned copy. The Clone method returns an OfficeObject. Cast the result to the element type (for example, (Paragraph)paragraph.Clone()).

    A paragraph copy contains copies of inline elements and has the same formatting settings, style name, and list settings as the source paragraph. A table copy contains copies of rows, cells, and cell content.

    An element can occur only once in a document fragment. If the document fragment already contains the element, Add and Insert methods throw an InvalidOperationException. To repeat an element in the same document fragment, add a copy.

    Added elements keep direct formatting settings and style names. If the target document does not contain a style with the same name, the element uses the default style. To keep style formatting settings, copy styles to the target document before you add the elements. If a paragraph is a list item, the API adds the numbering list to the WordDocument.NumberingLists collection of the target document.

    Note

    Bookmarks, comments, and range permissions are not document elements. To copy them with document content, insert a copy of a document range.

    The following code snippet copies the Heading 1 style and the Budget Overview section (a heading, two paragraphs, and a table) from Document.docx to a new document, and saves the new document to a DOCX file:

    using System.IO;
    using System.Linq;
    using DevExpress.Docs.Word;
    
    using var inputStream = File.OpenRead("Document.docx");
    using var source = new WordDocument(inputStream);
    using var document = new WordDocument();
    
    // Copy the style of section headings to the new document.
    document.ParagraphStyles.Add(source.ParagraphStyles["Heading 1"].Clone());
    
    // Add copies of the "Budget Overview" section paragraphs and table to the new document.
    var heading = source.Body.OfType<Paragraph>().First(p => p.GetText().StartsWith("Budget Overview"));
    for (var i = source.Body.IndexOf(heading); i < source.Body.Count; i++) {
        var block = source.Body[i];
        if (block != heading && block is Paragraph { StyleName: "Heading 1" })
            break;
        document.Body.Add((Block)block.Clone());
    }
    
    Directory.CreateDirectory("output");
    using var outputStream = File.Create(Path.Combine("output", "Document.docx"));
    document.Save(outputStream, DocumentFormat.Docx);
    

    Refer to the following help topics for additional information: