开发者

Interop Word - Delete Page from Document

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开发者_如何学Go 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.


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;
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜