wordpress hit counter
retrieve cursor position in a docx file - .Net - Development Tools - OpenXML Developer

retrieve cursor position in a docx file

Development Tools

Discussions about working with Open XML using a wide range of development tools

retrieve cursor position in a docx file

  • rated by 0 users
  • This post has 3 Replies |
  • 1 Follower
  • J have a template docx file opened.
    J want to add a text field where the cursor is positioned. Is it possible?
    How can j solve using c#?

    thanks in advance

    scaglio
  • Hi scaglio

    This code should do what you're wanting:

    /// <summary>
    /// Inserts the given <param name="text"/> at the cursor bookmark in the <param name="docName"/>
    /// </summary>
    /// <param name="docName">Name of the document.</param>
    /// <param name="text">The text to insert into the document.</param>
    public static void InsertTextBeforeCursorInWordprocessingDocument(string docName, string text)
    {
        // Open the Wordprocessing document.
        using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(docName, true))
        {

            BookmarkStart cursorBookmark = wordprocessingDocument.MainDocumentPart.Document.Body.Descendants<BookmarkStart>().Where(
                bookmarkStart => bookmarkStart.Name.HasValue && bookmarkStart.Name.Value.Equals("_GoBack")).SingleOrDefault();

            if (cursorBookmark != null)
            {
                Text docText = new Text(text);

                Run run = new Run(docText);

                cursorBookmark.Parent.InsertBefore(run, cursorBookmark);
            }

            // Save changes to the main document part.
            wordprocessingDocument.MainDocumentPart.Document.Save();
        }
    }

    Hope this helps :)
  • Thanks a lot Intergen, your code is very usefull.

    J have one problem:
    my docx is already opened in a word session, when I try to execute this code :"WordprocessingDocument.Open(docName, true)" I receive an error ('File already used by another process').
    Do you know how to solve this problem?

    thanks

    scaglio
  • Hi scaglio

    Yes, You simply need to make sure the document isn't opened by Office or another application (or possibly other code you have running) - ultimately you could restart your pc to ensure no application is using it and then try again (if still a problem check the file's properties do not have it set to read only or locked).
Page 1 of 1 (4 items)