C# Word Insert Page numbers in Footer
To use this code you need to add reference to the word object. See this post.
To insert page numbers automatically to your word document is super easy.
The steps are always.
1. Open the word document
2. Insert page number (in footer)
3. Save the document to a new location
4. quit application.
Here is the code to do that.
string inputFilePath = @"C:\Documents and Settings\prgu\My Documents\myinputfile.doc";
string outPutFilePath = @"C:\Documents and Settings\prgu\My Documents\myoutputfile.doc";
object Missing = System.Reflection.Missing.Value;
object fileToOpen = (object)@inputFilePath;
object fileToSave = (object)@outPutFilePath;
Word.Application app = new Word.ApplicationClass();
Word.Document doc = new Word.Document();
//set this to true, else it will actually open the word file in MS word
object myreadonly = true;
//open the word document
doc = app.Documents.Open(ref fileToOpen,
ref Missing, ref myreadonly, ref Missing, ref Missing,
ref Missing, ref Missing, ref Missing, ref Missing,
ref Missing, ref Missing, ref Missing, ref Missing,
ref Missing, ref Missing, ref Missing);
//Insert Page numbers
Word.Window activeWindow = doc.Application.ActiveWindow;
//define a currentpage object
object currentPage = Word.WdFieldType.wdFieldPage;
activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
//set alignment
activeWindow.ActivePane.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
//Add page number
activeWindow.Selection.Fields.Add(
activeWindow.Selection.Range, ref currentPage, ref Missing, ref Missing);
// Go back to the Main Document view
activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
//Finally we will save and close the doc
doc.SaveAs(ref fileToSave,
ref Missing, ref Missing, ref Missing, ref Missing,
ref Missing, ref Missing, ref Missing, ref Missing,
ref Missing, ref Missing, ref Missing, ref Missing,
ref Missing, ref Missing, ref Missing);
app.NormalTemplate.Saved = true;
doc.Close(ref Missing, ref Missing, ref Missing);
app.Quit(ref Missing, ref Missing, ref Missing);

