Not able to copy specific pages of word document

非 Y 不嫁゛ 提交于 2019-12-11 23:19:20

问题


I am trying to cut specific pages of my word document(.docx), say 2, 4. I am using for loop to traverse as per the page gave splitting it based on ,.Below is the code for the same

if (startEnd.Contains(','))
{
    arrSpecificPage = startEnd.Split(',');

    for (int i = 0; i < arrSpecificPage.Length; i++)
    {
        range.Start = doc.GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToAbsolute, arrSpecificPage[i]).Start;
        range.End = doc.GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToAbsolute, arrSpecificPage[i]).End;
        range.Copy();
        newDocument.Range().Paste();                    
    }
    newDocument.SaveAs(outputSplitDocpath);
}

but the issue with this code is that its just copying the last page only to the new document i.e 4 in this case. How to add 2 as well? What's wrong in the code?


回答1:


Since you always specify the entire document "range" as the target, each time you paste the entire content of the document is replaced.

It's correct that you work with a Range object and not with a selection, but it helps if you think about a Range like a selection. If you select everything (Ctrl+A) then paste, what was selected is replaced by what is pasted. Whatever is assigned to a Range will replace the content of the Range.

The way to solve this is to "collapse" the Range - think of it like pressing the Right-arrow or left-arrow key to "collapse" a selection to its start or end point. In the object model, this is the Collapse method that takes a parameter indicating whether to collapse to the start or end point (see the code below).

Note that I've also changed the code to use document.Content instead of Document.Range. Content is a property that returns the entire body of the document; Rangeis a method that expects a start and end point defining a Range. Using the property is the preferred method for the entire document.

if (startEnd.Contains(','))
{
    arrSpecificPage = startEnd.Split(',');

    for (int i = 0; i < arrSpecificPage.Length; i++)
    {
        range.Start = doc.GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToAbsolute, arrSpecificPage[i]).Start;
        range.End = doc.GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToAbsolute, arrSpecificPage[i]).End;
        range.Copy();
        Word.Range targetRange = newDocument.Content
        targetRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
        targetRange.Paste();                    
    }
    newDocument.SaveAs(outputSplitDocpath);
}


来源:https://stackoverflow.com/questions/52554269/not-able-to-copy-specific-pages-of-word-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!