none
How do I keep WholeStory together when pasting into new document? RRS feed

  • Question

  • I am looping through several word .docx files and merging them into a new document. The files consist of 2-3 paragraphs and a signature block. I found the code below and it works great, except that it goes to the next page and separates the paragraphs and signature block depending on space left in the new document. This makes sense, but I can't find a way to go to the next page if WholeStory won't fit on the current page. 

    oRng = mergeDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    
                        Word._Document copyFromDoc = mergeApp.Documents.Open(getDoc);
                        copyFromDoc.ActiveWindow.Selection.WholeStory();
    
                        copyFromDoc.ActiveWindow.Selection.Copy();
    
                        //var merged_data = copyFromDoc.ActiveWindow.Selection;
                        //object new_page = Word.WdGoToDirection.wdGoToNext;
    
                        // If merged_data fits on current page - Paste
                        // Else, go to new page and Paste
    
    
                        mergeDoc.ActiveWindow.Selection.Paste();
                       
                        copyFromDoc.Close();                   

    Wednesday, June 3, 2015 4:03 PM

Answers

  • Hi W.

    You can force Word to keep blocks of text together on a page by activating the "Keep With Next" and "Keep Together" paragraph formatting options. The first keeps each paragraph having the formatting on the same page with the following paragraph; the second keeps all lines of a paragraph on the same page. Logically, the LAST paragraph of the block should NOT be formatted "Keep with Next" - if all paragraphs are formatted thusly, then there is no effect as Word would have no way breaking to a new page so the setting would be ignored.

    In the object model, these are the Paragraph object properties KeepWithNext and KeepTogether.

    FWIW, it's usually more efficient to work with the Range.FormattedText property instead of activating windows, changing the Selection and copying/pasting. More like:

    oRng.FormattedText = copyFromDoc.Content.FormattedText;

    There are special cases where this does not provide exactly the same result as copying/pasting an entire document, but you might want to test (if you haven't already)...


    Cindy Meister, VSTO/Word MVP, my blog

    Wednesday, June 3, 2015 5:19 PM
    Moderator