Home > Articles > .Net Framework Articles > Working with Images in Word document in C#

Working with Images in Word document in C#

by Michael Brown   on Jan 25, 2018   Category: .Net Framework  | Level: Beginner  |  Views: 157    |  Points: 100   
Like this article? Bookmark and Share:
In this article, you will learn how to add images and handle existing images in Word document programmatically using C#.

Introduction

Microsoft Word as one of the most popular word processor, offers developers powerful and easy solutions to add and edit varies contents such as text and image. Image in a Word document can give clearer explanation than text, besides, it can also make the content more colorful and easy to understand. Many Word developers like adding images into Word document for different reasons and sometimes they also need to deal with existing images in Word document.

This article is going to explain how to add image into word document and handle existing images in word document using C#. This guide introduces an easy solution provided by Free Spire.Doc library.


The concrete operations we’re going to learn

Add Image into word document:

  1. Add inline image
  2. Add absolute positioned image

Handle existing image in word document:

  1. Resize image
  2. Rotate image
  3. Replace image with text
  4. Replace image with new image
  5. Extract image from word document
  6. Delete image from word document


Prerequisites required before coding

-> Create a new C# project in Visual Studio

-> Reference free Spire.Doc dll into project


Codes to add and handle images

Add Image into word document

Free Spire.Doc library supports adding both inline images and absolute positioned images into a Word document. The position of the inline image is constrained to the lines of text, while the absolute positioned image can be placed anywhere irrespective of the lines of text.

1. Add inline image

Document document = new Document();

Section section = document.AddSection();

 

Paragraph paragraph = section.AddParagraph();

paragraph.AppendText("Adding inline image");

paragraph.ApplyStyle(BuiltinStyle.Heading1);

 

DocPicture picture = paragraph.AppendPicture(Image.FromFile(@"1.jpg"));

 

picture.Width = 120f;

picture.Height = 170f;

 

document.SaveToFile("InlineImage.docx", FileFormat.Docx);


2. Add absolute positioned image

Document document = new Document();

Section section = document.AddSection();

Paragraph paragraph = section.AddParagraph();


paragraph.AppendText("Adding absolute positioned image into a Word document");

paragraph.ApplyStyle(BuiltinStyle.Heading1);


DocPicture picture = paragraph.AppendPicture(Image.FromFile(@"1.jpg"));

picture.TextWrappingStyle = TextWrappingStyle.Square; 


picture.HorizontalPosition = 180f;

picture.VerticalPosition = 60f;

 

picture.Width = 120f;

picture.Height = 170f;

 

document.SaveToFile("PositionedImage.docx", FileFormat.Docx);


Handle existing image in word document

Images existing in a Word document can be accessed by iterating through the child objects of the paragraphs, next we’re able to operate these images by using DocPicture class. In this part we’ll learn how to resize, rotate, replace, extract and delete images in a Word document.

1. Resize image

Document document = new Document("PositionedImage.docx");

Section section = document.Sections[0];

Paragraph paragraph = section.Paragraphs[0];

 

foreach (DocumentObject docObj in paragraph.ChildObjects)

{

    if (docObj is DocPicture)

    {

        DocPicture picture = docObj as DocPicture;

        picture.Width = 50f;

        picture.Height = 50f;

    }

} 

document.SaveToFile("ResizeImage.docx");


2. Rotate image

Document document = new Document("PositionedImage.docx");

Section section = document.Sections[0];

Paragraph paragraph = section.Paragraphs[0];

 

foreach (DocumentObject docObj in paragraph.ChildObjects)

{

    if (docObj is DocPicture)

    {

        DocPicture picture = docObj as DocPicture;

        Image image = picture.Image;

        image.RotateFlip(RotateFlipType.Rotate180FlipX);

        picture.LoadImage(image);

    }

}

document.SaveToFile("RotateImage.docx");


3. Replace image with text

Document document = new Document("PositionedImage.docx");

Section section = document.Sections[0];

Paragraph paragraph = section.Paragraphs[0];

 

int j = 1;

List<DocumentObject> pictures = new List<DocumentObject>();

foreach (DocumentObject docObj in paragraph.ChildObjects)

{

    if (docObj is DocPicture)

    {

        pictures.Add(docObj);

    }

}

foreach (DocumentObject pic in pictures)

{

    int index = paragraph.ChildObjects.IndexOf(pic);

    TextRange range = new TextRange(document);

    range.Text = string.Format(" Image {0}", j);

    paragraph.ChildObjects.Insert(index, range);

    paragraph.ChildObjects.Remove(pic);

    j++;

} 

document.SaveToFile("ReplaceImageWithText.docx", FileFormat.Docx);


4. Replace image with new image

Document document = new Document("Sample.docx");

Section section = document.Sections[0];

Paragraph paragraph = section.Paragraphs[0];

 

foreach (DocumentObject docObj in paragraph.ChildObjects)

{

    if (docObj is DocPicture)

    {

        DocPicture picture = docObj as DocPicture;

        if (picture.Title == "Figure 1")

        {

            picture.LoadImage(Image.FromFile("timg.jpg"));

        }

    }

}

 

document.SaveToFile("ReplaceImageWithImage.docx");


5. Extract image from word document

Document document = new Document("PositionedImage.docx");


int index = 0;

foreach (Section section in document.Sections)

{

    foreach (Paragraph paragraph in section.Paragraphs)

    {

        foreach (DocumentObject docObject in paragraph.ChildObjects)

        {

            if (docObject is DocPicture)

            {

                DocPicture picture = docObject as DocPicture;

                String imageName = String.Format(@"Image-{0}.png", index);

                picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);

                index++;

            }

        }

    }

}


6. Delete image from word document

Document document = new Document("PositionedImage.docx");

 

foreach (Section section in document.Sections)

{

    foreach (Paragraph paragraph in section.Paragraphs)

    {

        for (int i = paragraph.ChildObjects.Count - 1; i >= 0; i--)

        {

            if (paragraph.ChildObjects[i] is DocPicture)

            {

                    DocPicture picture = paragraph.ChildObjects[i] as DocPicture;

                    paragraph.ChildObjects.Remove(picture);

 

            }

        }

    }

}

 

document.SaveToFile("DeleteImage.docx", FileFormat.Docx2013);


Conclusion

Hope you now understand how to work with images in Word documents programmatically.





Like this article? Bookmark and Share:

Most viewed Articles

User Comments


No response found, be the first to review this article.

Submit feedback about this article

Please sign in to post feedback

Latest Posts