none
Moving cursor/insertion point to start of word document and insert new content from that point RRS feed

  • Question

  • I've originally posted the thread to C# general and was asked to post into Word Dev Forum. Sorry for double post.

    As the title suggest, I'm trying to create word document through C#. I'm able to create new document, but I also want to open an existing document and add the content to it from the beginning. That is I want the new content to appear at the top. Below is what I've done so far, but always the content gets appended at the end.

    using System.IO;
    using Word = Microsoft.Office.Interop.Word;
    namespace Snapper
    {
        class WordDocumentGenerator
        {
            public void CreateWordDocument(string fileName)
            {
                string originalPath = Directory.GetCurrentDirectory();
                string path = originalPath;
                path += @"\snapshots";
                object oMissing = System.Reflection.Missing.Value;
                
                //Create a new Word Application
                Word._Application wordApp = new Word.Application();
                wordApp.Visible = false;
                try
                {
                    //Create a new blank document
                    object filePath = originalPath + @"\documents" + @"\TSC1.doc";
                    Word._Document doc = wordApp.Documents.Open(ref filePath,
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing,                                                            
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing,
                                                                ref oMissing);
                    string[] images = Directory.GetFiles(path);
                    //Create a range
                    object what = Word.WdGoToItem.wdGoToLine;
                    object which = Word.WdGoToDirection.wdGoToFirst;
                    object myTrue = true;
                    object myFalse = false;
                    doc.GoTo(ref what, ref which, ref oMissing, ref oMissing);
                    
                    //Insert filename as header
                    var pText = doc.Paragraphs.Add(ref oMissing);
                    pText.Format.SpaceAfter = 10f;
                    pText.Range.Text = fileName;
                    pText.Range.InsertParagraphAfter();
                    foreach (var image in images)
                    {                  
                        var pImage = doc.Paragraphs.Add(ref oMissing);
                        pImage.Format.SpaceAfter = 10f;
                        object myRng = pImage.Range;
                        doc.InlineShapes.AddPicture(image, ref myFalse, ref myTrue, ref myRng);
                    }                
                    path = originalPath;
                    path += @"\documents";
                    DirectoryInfo docDir = new DirectoryInfo(path);
                    if (!docDir.Exists)
                    {
                        docDir.Create();
                    }
                    object savePath = path + @"\" + fileName + ".doc";
                    doc.SaveAs(ref savePath,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing
                       );
                    doc.Save();
                }            
                finally
                {
                    wordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                }                                                                          
            }
            
        }
    }

    The document which I want my new content to be inserted already contain a series of text and images.
    I've also tried the combination of

    object units = Word.WdUnits.Story;
    wordApp.Selection.HomeKey(ref units, ref oMissing);
    var pText = doc.Paragraphs.Add(ref oMissing);  
    pText.Format.SpaceAfter = 10f;  
    pText.Range.InsertParagraphAfter();  

    Then I got advice to select the range of entire document and try to insert the new content

    Word.Range rng; 
    object start = 0;
    object end = 0;
    object finalRng;
    rng = Word.ActiveDocument.Range(ref start, ref end);
    finalRng = rng;

    Now I'm able to move the cursor to beginning of doucment.

    I've created a range object and set its start and end refereces to 0 and 0. Now the content gets inserted to the beginning but there is a little problem in that insertion. The new content gets inserted upside down in the order of insertion. i.e. The first piece of content goes to the last and the second one goes previous to the last and so on until the last content becomes the first. What I haven't tried is using the praragraphs[1].range yet.

    BTW this is the code that I'm using to insert my new content

    I'm looping through a List of strings which contains either text or path of the image. So my loop will decide what is the current iteration and will insert a paragraph

    //Before going into this for loop, I want my cursor/insertion point to be positioned
    //at the top/starting of document and then insert the content one below the another through
    //following looping condtruct.
    for (var i = 0; i < 10; i++)
                {
                    // Insert text
                    var pText = document.Paragraphs.Add();
                    pText.Format.SpaceAfter = 10f;
                    pText.Range.Text = String.Format("This is line #{0}", i);
                    pText.Range.InsertParagraphAfter();
                    
                    // Insert picture
                    var pPicture = document.Paragraphs.Add();
                    pPicture.Format.SpaceAfter = 10f;
                    document.InlineShapes.AddPicture(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "img_1.png"), Range: pPicture.Range);
                }
    Can anyone provide me a solution to move the cursor to top of document and insert my new content from there.
    Thursday, February 21, 2013 6:59 AM

Answers

  • Hi kunakuvarem

    I've deleted the duplicate post that was moved here from the other forum as it didn't contain any useful discussion - just FYI in case you go looking for it or get an alert.

    If you think about it, it's logical that, given a Range point at the beginning of the document anything you insert will always go in at the beginning.

    One possible solution would be to simply reverse your loop: for (var i=10;i>0;i--)

    That approach would be simplest. An alternative would be to re-assign the Range starting point to the last Range you've inserted, which would be pPicture.Range. This would mean that you need a Range starting point going into the loop. So something like this, perhaps:

      object oCollapseStart = Word.WdCollapseDirection.wdCollapseStart;
      object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
      Word.Range rngInsertNew = document.Content;
      rngInsertNew.Collapse(ref oCollapseStart);
      for (var i = 0; i < 10; i++)
               
    {
                   
    // Insert text
                   
    var pText = rngInsertNew.Paragraphs.Add();
                   //Do other things
                  var pPicture = rngInsertNew.Paragraphs.Add();
                  rngInsertNew = pPicture.Range.Duplicate;
                  rngInsertNew.Collapse(ref oCollapseEnd);
                 }


    Cindy Meister, VSTO/Word MVP, my blog

    Friday, February 22, 2013 8:26 AM
    Moderator