Search code examples
asp.netoffice-interop

just first page in accessible in Microsoft.Office.Interop.Word


I use following code to access a word file pages. but it has error when I try to access the page 2 (pg[2]) or (pg[0])... I just can access pg[1]! when I try to access other pages I receive this error: The requested member of the collection does not exist.

    Word._Application oWord = new Word.Application();
    // Make this instance of word invisible (Can still see it in the taskmgr).
    oWord.Visible = false;

    // Interop requires objects.
    object oMissing = System.Reflection.Missing.Value;

    // Load a document into our instance of word.exe
    Word.Document oDoc = oWord.Documents.Open(ref fileName, 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);

    // Make this document the active document.
    oDoc.PrintPreview();
    oDoc.Activate();
    foreach (Microsoft.Office.Interop.Word.Window window in oDoc.Windows)
    {
        foreach (Microsoft.Office.Interop.Word.Pane pan in window.Panes)
        {

            Microsoft.Office.Interop.Word.Pages pg = pan.Pages;
            Microsoft.Office.Interop.Word.Page pg1 = pg[1];
            Microsoft.Office.Interop.Word.Page pg2 = pg[2];
        }
    }

Solution

  • Spent hours on the same issue. And here's how I managed to solve it:

    Word.Page page;
    
    while (true) {
        try {
            // Load this page manually.
            window.Selection.GoTo(Word.WdGoToItem.wdGoToPage, Type.Missing, i, Type.Missing);
            page = pages[i];
    
            break;
        } catch (Exception e) {
            // If not error "The requested member of the collection does not exist."
            if ((uint)e.HResult != 0x800A1735) {
                throw;
            }
    
            Thread.Sleep(500);
        }
    }
    

    By the way, you can actually access the pages by:

    var window = document.ActiveWindow;
    var pane = window.ActivePane;
    var pages = pane.Pages;
    

    Wrote a post about issues I solved related http://vane.life/2015/08/03/use-office-interop-on-iis/, hope that will also help.