简体   繁体   中英

How to check on which page of a word document a shape/image is located using C# Interop

Using

var shapes = currentDocument.Shapes;
foreach (Shape shape in shapes)
    if (shape.Type == MsoShapeType.msoPicture)
    {
        InlineShapeHelper.ReplaceInlineShape(...);
        break;
    }

I can replace the first image in "currentDocument".

How can I detect on which page the image is located (or in this case also sufficient: if it's on the first page)?

I want to replace an specific image on the first page, so is it maybe even possible to extract the image or check otherwise if the image is the one I'm looking for?

To answer your specific question: How can I detect on which page the image is located?

The get_Information method can return the page number of a given Range using the enumeration Word.WdInformation.wdActiveEndPageNumber .

A Shape is always anchored to a specific character in the document - this is the Range property of the Shape ( Shape.Anchor ).

The following code sample demonstrates how to loop the Shapes in a document, get their name and page number. Note that if the Shape.Name is known it's possible to pick up a Shape object directly ( Shapes["Name As String"] ). But you need to be careful with names generated by the Word application when Shape is inserted as Word can change the name it assigns itself at any time. If a name is assigned using code that name remains static - Word won't change it.

         Word.ShapeRange shpRange = doc.Content.ShapeRange;
        foreach (Word.Shape shp in shpRange)
        {
            System.Diagnostics.Debug.Print(shp.Name + ", " + shp.Anchor.get_Information(Word.WdInformation.wdActiveEndPageNumber).ToString());
        }

One way I found just after posting the question is to generate the hash-code of the image:

var shapes = currentDocument.Shapes;
foreach (Shape shape in shapes)
    if (shape.Type == MsoShapeType.msoPicture)
    {
        int hash = shape.GetHashCode();
        InlineShapeHelper.ReplaceInlineShape(...);
        break;
    }

But I would still be interested in other, better, more elegant solutions and the possibility to get to know the page number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM