views:

85

answers:

2

Hi,

What is the easiest and most efficient way to delete a specific page from a Document object using the Word Interop Libraries?

I have noticed there is a Pages property that extends/implements IEnumerable. Can one simply remove the elements in the array and the pages will be removed from the Document?

I have also seen the Ranges and Section examples, but the don't look very elegant to use.

Thanks.

+1  A: 

The short answer to your question is that there is no elegant way to do what you are trying to achieve.

Word heavily separates the content of a document from its layout. As far as Word is concerned, a document doesn't have pages; rather, pages are something derived from a document by viewing it in a certain way (e.g. print view). The Pages collection belongs to the Pane interface (accessed, for example, by Application.ActiveWindow.ActivePane), which controls layout. Consequently, there are no methods on Page that allow you to change (or delete) the content that leads to the existence of the page.

If you have control over the document(s) that you are processing in your code, I suggest that you define sections within the document that represent the parts you want to programmatically delete. Sections are a better construct because they represent content, not layout (a section may, in turn, contain page breaks). If you were to do this, you could use the following code to remove a specific section:

object missing = Type.Missing;
foreach (Microsoft.Office.Interop.Word.Section section in doc.Sections) {
    if (/* some criteria */) {
        section.Range.Delete(ref missing, ref missing);
        break;
    }
}
Bradley Smith
+1  A: 

One possible option is to bookmark the whole pages (Select the whole page, go to Tools | Insert Bookmark then type in a name). You can then use the Bookmarks collection of the Document object to refer to the text and delete it.

Alternatively, try the C# equivalent of this code:

Doc.ActiveWindow.Selection.GoTo wdPage, PageNumber
Doc.Bookmarks("\Page").Range.Text = ""

The first line moves the cursor to page "PageNumber". The second one uses a Predefined Bookmark which always refers to the page the cursor is currently on, including the the page break at the end of the page if it exists.

Foole
As a side note, I have found Range.Text = "" to be more reliable than Range.Delete as the former does not appear to be affected by the "smart cut and paste" option.
Foole
I see there is a Delete() function on the Bookmark itself. Is it possible to use the Delete() on the \Page bookmark to delete that page?
Koekiebox
Nope. That will attempt to delete the bookmark itself, which will cause Run-time error '5827': Predefined bookmarks cannot be modified.
Foole