Click here to Skip to main content
15,880,405 members
Please Sign up or sign in to vote.
3.75/5 (3 votes)
I am using Microsoft.Office.Interop.Word to generate word file using C#. While adding page number in footer some of the page number get repeated though section of each page is different. How can I manage to add distinct page number in word document?
Posted

You need to use the PageNumbers.Add method: https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.pagenumbers.add%28v=office.15%29.aspx[^]

wordDoc.Sections(1).Footers(1).PageNumbers.Add (1)
 
Share this answer
 
v2
Comments
Leo Chapiro 6-Feb-15 9:41am    
Thanks .NET DJ for adding an example !
Sanketk1790 9-Feb-15 1:54am    
I am using following code to generate page number & print it,But for some pages it is repeating the previous page number.
Sanketk1790 9-Feb-15 1:54am    
pageRange.InsertBreak(word.WdBreakType.wdSectionBreakContinuous);
pageRange.Select();
pageRange.Collapse(word.WdCollapseDirection.wdCollapseStart);

pageRange.Sections[1].Footers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].LinkToPrevious = false;
pageRange.Sections[1].Footers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Paragraphs.Alignment = word.WdParagraphAlignment.wdAlignParagraphRight;
pageRange.Sections[1].Footers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Font.Name = "Arial";
pageRange.Sections[1].Footers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Font.Size = 8f;
pageRange.Sections[1].Footers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = PrintPageNo(footerText, page1);
page1++;
pageRange.Collapse(word.WdCollapseDirection.wdCollapseEnd);
I moved from using Interop to OpenXML for my Word document manipulation needs, because I wanted to generate Word documents on the server and Microsoft advises not to use Interop for such scenarios - see KB 257757).

Since you have problems with pagination, consider using some 3rd party OpenXML toolkit. Because these toolkits are based on word templates, which get filled with data at runtime, you have all the native functionality of Word, including pagination, which could be set at template design. In your code you don't have to deal with it at all.

Take a look at this example at Code Project to find out more.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900