Skip to content

Commit f2fdf59

Browse files
Modified the image, template and code snippet
1 parent fc22372 commit f2fdf59

File tree

3 files changed

+12
-26
lines changed

3 files changed

+12
-26
lines changed
14 KB
Loading
Binary file not shown.

Paragraphs/Replace-image-with-same-size/Replace-image-with-same-size/Program.cs

Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -8,32 +8,18 @@
88
{
99
// Variables to store the original width and height of each picture.
1010
float pictureWidth, pictureHeight = 0;
11-
// Retrieve the body of the first section.
12-
WTextBody textbody = document.Sections[0].Body;
13-
// Iterates through each paragraph in the document's body.
14-
foreach (WParagraph paragraph in textbody.Paragraphs)
15-
{
16-
// Iterates through each item within the paragraph.
17-
foreach (ParagraphItem item in paragraph.ChildEntities)
18-
{
19-
// Checks if the item is a picture.
20-
if (item is WPicture)
21-
{
22-
// Casts the item to WPicture to access picture properties.
23-
WPicture picture = item as WPicture;
24-
// Store the original width and height of the picture.
25-
pictureWidth = picture.Width;
26-
pictureHeight = picture.Height;
27-
// Open the new image file to replace the existing picture.
28-
FileStream imageStream = new FileStream(Path.GetFullPath(@"Data/Image.png"), FileMode.Open, FileAccess.ReadWrite);
29-
// Load the new image into the existing picture element.
30-
picture.LoadImage(imageStream);
31-
// Restore the original width and height to maintain the picture's dimensions.
32-
picture.Width = pictureWidth;
33-
picture.Height = pictureHeight;
34-
}
35-
}
36-
}
11+
// Find the picture with alternative text.
12+
WPicture picture = document.FindItemByProperty(EntityType.Picture, "AlternativeText", "Adventure") as WPicture;
13+
// Store the original width and height of the picture.
14+
pictureWidth = picture.Width;
15+
pictureHeight = picture.Height;
16+
// Open the new image file to replace the existing picture.
17+
FileStream imageStream = new FileStream(Path.GetFullPath(@"Data/Image.png"), FileMode.Open, FileAccess.ReadWrite);
18+
// Load the new image into the existing picture element.
19+
picture.LoadImage(imageStream);
20+
// Restore the original width and height to maintain the picture's dimensions.
21+
picture.Width = pictureWidth;
22+
picture.Height = pictureHeight;
3723
using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite))
3824
{
3925
// Saves the modified Word document.

0 commit comments

Comments
 (0)