I have to open Word documents for automation in read only mode. Then I have to remove some certain pages from that document, regarding some configuration the user did in the user interface of the program.
Manipulation does work for footers and headers, but this particular code doesn't work. It breaks with error System.Runtime.InteropServices.COMException (0x800A11FD): This method or property is not available because this command is not available for reading. when executing this code:
int num = objWordDoc.ComputeStatistics(stat, ref missing);
int[] a = { 1,3,5};
for (int i = 0; i < a.Length; i++)
{
object page_num = a[i];
objWordDoc.Application.Selection.GoTo(Word.WdGoToItem.wdGoToPage,
Word.WdGoToDirection.wdGoToAbsolute, num, page_num);
objWordDoc.Application.Selection.Bookmarks[@"\Page"].Select();
objWordDoc.Application.Selection.Delete();
}
in the line where Selection.Goto is called. This code has been taken from How to delete pages in a word document dynamically.
Working with the document does work, when the user has followed the procedure described in http://myitforum.com/myitforumwp/2013/06/10/disable-reading-mode-and-protected-view-in-word-2013/. Mainly a setting has to be disabled: To disable the Reading View. Go to File – Options – General. Uncheck “Open E-Mail attachments and other uneditable files in reading view”
This only seems to be necessary for Word 2013, as Word 2010 works fine. Is it possible to force edit mode programmatically without the necessity to let the user define those settings?
--- UPDATE ---
Reasons why using this approach:
- opening office documents in readonly mode is necessary if multiple programs try to access the same document. Otherwise word would raise a message box trying to clarify who is the one that is allowed to edit the document.
- Actually this procedure works fine in Word 2010
- open in read only mode doesn't mean, editing of the document is locked, it does mean, the document has to be saved under a different name/ location while editing is fully possible. This behavior seems to be changed by Word 2013.
In order to turn off ReadingMode your need to put this at the beginning of your code
Globals.ThisAddIn.Application.Options.AllowReadingMode = false;
You may get errors because of the direction of your loop. Your first page is page 1 once you delete this then page 2 becomes page 1 etc
If you reverse this and remove the last page first then it will remove the correct page.
Hope this helps. My sample above is from a Application level addin. I've tested it on 2013 and it appears to work