如何使用 C# Interop 检查 shape/image 位于 word 文档的哪一页
How to check on which page of a word document a shape/image is located using C# Interop
正在使用
var shapes = currentDocument.Shapes;
foreach (Shape shape in shapes)
if (shape.Type == MsoShapeType.msoPicture)
{
InlineShapeHelper.ReplaceInlineShape(...);
break;
}
我可以替换"currentDocument"中的第一张图片。
如何检测图像位于哪个页面(或者在这种情况下也足够:如果它在第一页)?
我想替换第一页上的特定图片,所以是否可以提取图片或以其他方式检查图片是否是我要查找的图片?
我在发布问题后发现的一种方法是生成图像的哈希码:
var shapes = currentDocument.Shapes;
foreach (Shape shape in shapes)
if (shape.Type == MsoShapeType.msoPicture)
{
int hash = shape.GetHashCode();
InlineShapeHelper.ReplaceInlineShape(...);
break;
}
但我仍然会对其他更好、更优雅的解决方案以及了解页码的可能性感兴趣。
回答您的具体问题:如何检测图片位于哪个页面?
get_Information
方法可以 return 使用枚举 Word.WdInformation.wdActiveEndPageNumber
.
给定 Range
的页码
A Shape
始终锚定到文档中的特定字符 - 这是形状 (Shape.Anchor
) 的 Range
属性。
以下代码示例演示了如何循环文档中的形状,获取它们的名称和页码。请注意,如果 Shape.Name
已知,则可以直接拾取 Shape
对象 (Shapes["Name As String"]
)。但是您需要注意插入 Shape 时 Word 应用程序生成的名称,因为 Word 可以随时更改它分配给自己的名称。如果名称是使用代码分配的,该名称将保持静态 - Word 不会更改它。
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());
}
正在使用
var shapes = currentDocument.Shapes;
foreach (Shape shape in shapes)
if (shape.Type == MsoShapeType.msoPicture)
{
InlineShapeHelper.ReplaceInlineShape(...);
break;
}
我可以替换"currentDocument"中的第一张图片。
如何检测图像位于哪个页面(或者在这种情况下也足够:如果它在第一页)?
我想替换第一页上的特定图片,所以是否可以提取图片或以其他方式检查图片是否是我要查找的图片?
我在发布问题后发现的一种方法是生成图像的哈希码:
var shapes = currentDocument.Shapes;
foreach (Shape shape in shapes)
if (shape.Type == MsoShapeType.msoPicture)
{
int hash = shape.GetHashCode();
InlineShapeHelper.ReplaceInlineShape(...);
break;
}
但我仍然会对其他更好、更优雅的解决方案以及了解页码的可能性感兴趣。
回答您的具体问题:如何检测图片位于哪个页面?
get_Information
方法可以 return 使用枚举 Word.WdInformation.wdActiveEndPageNumber
.
Range
的页码
A Shape
始终锚定到文档中的特定字符 - 这是形状 (Shape.Anchor
) 的 Range
属性。
以下代码示例演示了如何循环文档中的形状,获取它们的名称和页码。请注意,如果 Shape.Name
已知,则可以直接拾取 Shape
对象 (Shapes["Name As String"]
)。但是您需要注意插入 Shape 时 Word 应用程序生成的名称,因为 Word 可以随时更改它分配给自己的名称。如果名称是使用代码分配的,该名称将保持静态 - Word 不会更改它。
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());
}