3
votes

I have copied contents of one word document to another word document using C# through a forum here. Copy text from word file to a new word

I used the second solution. This part took care of the copying the whole document along with the formatting,

static MSWord.Document CopyToNewDocument(MSWord.Document document)
{
document.StoryRanges[MSWord.WdStoryType.wdMainTextStory].Copy();
var newDocument = document.Application.Documents.Add();
newDocument.StoryRanges[MSWord.WdStoryType.wdMainTextStory].Paste();
return newDocument;
}

Now I would like to specify a page range,from the user, like start page number & end page number, and copy the selected range alone to an another word document along with preserving the formatting.. Any help in this will be highly appreciated .....

1

1 Answers

2
votes

You might want to have a look at http://social.msdn.microsoft.com/Forums/office/en-US/e48b3126-941d-490a-85ee-e327bbe7e81b/convert-specific-word-pages-to-pdf-in-c?forum=worddev

It shows how you can get a specific range of pages from a word document (with preserved formatting).

Relevant parts (in case the linked page vanishes):

Open an instance of word.

  Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

And load your document. After opening the file you have to prepare the range for your selection. Count and count2 are the page numbers that you would provide in your special case.

  object what = WdGoToItem.wdGoToPage;
  object which = WdGoToDirection.wdGoToFirst;
  object count = 1;
  Range startRange = word.Selection.GoTo(ref what, ref which, ref count, ref oMissing);
  object count2 = (int)count + 3;
  Range endRange = word.Selection.GoTo(ref what, ref which, ref count2, ref oMissing);
  endRange.SetRange(startRange.Start, endRange.End - 1);
  endRange.Select();

Selection.Copy() then copies the selected pages to the Clipboard while preserving the formatting.

  word.Selection.Copy();

The rest of the source creates a new document in which your selection is pasted.

  word.Documents.Add();
  word.Selection.Paste();

  object outputFileName = "d:\\test1.doc";
  object fileFormat = WdSaveFormat.wdFormatDocument97;

  word.ActiveDocument.SaveAs(ref outputFileName,
      ref fileFormat, 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);

I hope this helps a bit.