Gunti Dilip

Gunti Dilip

  • NA
  • 54
  • 103.9k

How to unlink footer and headers in word using C# ?

Nov 15 2013 4:31 AM
Hi,

I am trying to merge word documents. When i am trying merge i am getting the previous documents header & footer in second document. Please tell me how to set link to previous false.

Please Find below code..

object missing = Type.Missing;
                Word.Application objWordApp = new Word.Application();
                Word.Document objWordDoc = new Word.Document();
                Word.Range wrdRange = objWordDoc.Range(ref missing, ref missing);
                Word.Section wrdSection = wrdRange.Sections.Add(ref missing, ref missing); 
                object objSectionBreakNextPage = Word.WdBreakType.wdSectionBreakNextPage;
                
                object objDestinationDoc = "E:\\MergeTemplates\\Test.doc";

                object sourceFileName1 = @"E:\MergeTemplates\Document1.doc";
                var varSourceDoc1 = objWordApp.Documents.Open(sourceFileName1, false, false, ref missing,
                                        ref missing, ref missing, ref missing, ref missing,
                                        ref missing, ref missing, ref missing, true,
                                        ref missing, ref missing, ref missing, ref missing);
                varSourceDoc1.Activate();
                varSourceDoc1.ActiveWindow.Selection.WholeStory();
                varSourceDoc1.ActiveWindow.Selection.Copy();
                varSourceDoc1.Close(false);

                objWordDoc = objWordApp.Documents.Add(ref missing, ref missing, ref missing, true);
                objWordDoc.Activate();
                objWordDoc.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdFormatOriginalFormatting);

                wrdSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].LinkToPrevious = false;
                wrdSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText = objWordDoc.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText;

                wrdSection.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].LinkToPrevious = false;
                wrdSection.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText = objWordDoc.Sections[1].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText;

                objWordApp.Selection.InsertBreak(ref objSectionBreakNextPage);
                objWordApp.ActiveDocument.SaveAs(objDestinationDoc, ref missing, ref missing,
                                                ref missing, ref missing, ref missing, ref missing,
                                                ref missing, ref missing, ref missing, ref missing);
                objWordApp.ActiveDocument.Close(ref missing, ref missing, ref missing);