Friday, 30 December 2022 06:15

C#/VB.NET: Replace Images in Word Documents

Sometimes you may encounter a situation where you need to replace images in a Word document. For example, if you are creating a resume from a template, you may need to replace the profile picture in the template with your own photo. In this article, we will show you how to replace images in a Word document in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Replace Image with New Image in Word in C# and VB.NET

To replace an image in a Word document with another image, you need to loop through the elements of the document, find the images and add them to a list, then get the image that you want to replace from the list and call the DocPicture.LoadImage() method to replace it with another image.

The following are the detailed steps:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Initialize an instance of the List class.
  • Iterate through all sections in the document.
  • Iterate through all paragraphs in each section.
  • Iterate through all child objects in each paragraph.
  • Find the images and add them to the list.
  • Get a specific image from the list and replace it with another image using DocPicture.LoadImage() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Collections.Generic;
using System.Drawing;

namespace ReplaceImageWithImage
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc = new Document();
            //Load a Word document
            doc.LoadFromFile("Sample.docx");

            //Initialize an instance of the List class
            List pictures = new List();

            //Iterate through all sections in the document
            foreach (Section sec in doc.Sections)
            {
                //Iterate through all paragraphs in each section
                foreach (Paragraph para in sec.Paragraphs)
                {
                    //Iterate through all child objects in each paragraph
                    foreach (DocumentObject docObj in para.ChildObjects)
                    {
                        //Find the images and add them to the list
                        if (docObj.DocumentObjectType == DocumentObjectType.Picture)
                        {
                            pictures.Add(docObj);
                        }
                    }
                }
            }

            //Replace the first picture in the list with another image
            DocPicture picture = pictures[0] as DocPicture;
            picture.LoadImage(Image.FromFile(@"doc.png"));

            //Save the result document
            doc.SaveToFile("ReplaceWithNewImage.docx", FileFormat.Docx2013);

        }
    }
}

C#/VB.NET: Replace Images in Word Documents

Replace Image with Text in Word in C# and VB.NET

Spire.Doc doesn’t provide a direct method to replace image with text, but you can achieve this task by inserting the text at the image location and then removing the image from the document.

The following steps demonstrate how to replace all images in a Word document with text:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Iterate through all sections in the document.
  • Iterate through all paragraphs in each section.
  • Initialize an instance of the List class.
  • Iterate through all child objects in each paragraph.
  • Find the images and add them to the list.
  • Iterate through the images in the list.
  • Get the index of the image in the paragraph using Paragraph.ChildObjects.Indexof() method.
  • Initialize an instance of TextRange class and set text for the text range through TextRange.Text property.
  • Insert the text range at the image location using Paragraph.ChildObjects.Insert() method.
  • Remove the image from the paragraph using Paragraph.ChildObjects.Remove() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Collections.Generic;

namespace ReplaceImageWithText
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc = new Document();
            //Load a Word document
            doc.LoadFromFile("Sample.docx");

            int j = 1;
            //Iterate through all sections in the document
            foreach (Section sec in doc.Sections)
            {
                //Iterate through all paragraphs in each section
                foreach (Paragraph para in sec.Paragraphs)
                {
                    //Initialize an instance of the List class
                    List pictures = new List();
                    //Find the images and add them to the list
                    foreach (DocumentObject docObj in para.ChildObjects)
                    {
                        if (docObj.DocumentObjectType == DocumentObjectType.Picture)
                        {
                            pictures.Add(docObj);
                        }
                    }

                    //Iterate through all images in the list and replace them with text "Here is image {image index}"
                    foreach (DocumentObject pic in pictures)
                    {
                        int index = para.ChildObjects.IndexOf(pic);
                        TextRange range = new TextRange(doc);
                        range.Text = string.Format("Here is image-{0}", j);
                        para.ChildObjects.Insert(index, range);
                        para.ChildObjects.Remove(pic);
                        j++;
                    }
                }
            }

            //Save the result document
            doc.SaveToFile("ReplaceWithText.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Replace Images in Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Image and Shape

Image can add interest and take effect to your Word documents. Suppose you've written an article introducing a city about its beautiful scenery. Just using words describe, you cannot present perfect scenery to your readers, because that page of text looks indistinct and dull. You need image to embellish your scenery.

Spire.Doc for .NET, a professional .NET word component to fast generate, open, modify and save Word documents without using MS Office Automation, enables users to insert image into Word document and set its size according to page by using C#.NET. This guide introduces an easy method how to insert image via Spire.Doc for .NET.

At first, create new Word document and add section, paragraph for this document. Then, insert image in the new created paragraph. You can set this image's size, position, rotate it and choice the wrapping-style about the text. Download and Install Spire.Doc for .NET. Use the following code to insert image in Word by using C#.

The sample demo shows how to insert an image into a document.

Insert Image in Word Document

using System;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace Insert_image_to_Word_Document
{
    class Program
    {
        static void Main(string[] args)
        {
 //Open a blank word document as template
            Document document = new Document(@"Blank.doc");
            Section section = document.Sections[0];
            Paragraph paragraph
                = section.Paragraphs.Count > 0 ? section.Paragraphs[0] : section.AddParagraph();
            paragraph.AppendText("The sample demonstrates how to insert an image into a document.");
            paragraph.ApplyStyle(BuiltinStyle.Heading2);
            paragraph = section.AddParagraph();
  
            //get original image 
            Bitmap p = new Bitmap(Image.FromFile(@"Word.jpg")); 
           
            //rotate image and insert image to word document
            p.RotateFlip(RotateFlipType.Rotate90FlipX);

            DocPicture picture = document.Sections[0].Paragraphs[0].AppendPicture(p);
   
            //set image's position
            picture.HorizontalPosition = 50.0F;
            picture.VerticalPosition = 60.0F;

            //set image's size
            picture.Width = 200;
            picture.Height = 200;

            //set textWrappingStyle with image;
            picture.TextWrappingStyle = TextWrappingStyle.Through;

            //Save doc file.
            document.SaveToFile("Sample.doc", FileFormat.Doc);

            //Launching the MS Word file.            System.Diagnostics.Process.Start("Sample.doc");
        }
       }
}

If you have finished the tutorial Spire.Doc Quick Start, the steps above will be simpler.

With Spire.Doc, you can insert an image into your Word documents and do more same thing in your ASP.NET, WPF and Silverlight applications without Word automation and any other third party add-ins.

Published in Image and Shape

Extracting images from a Word document programmatically can be useful for automating document processing tasks. In this article, we’ll demonstrate how to extract images from a Word file using C# and the Spire.Doc for .NET library. Spire.Doc is a powerful .NET library that enables developers to manipulate Word documents efficiently.

Getting Started: Installing Spire.Doc

Before you can start extracting images, you need to install Spire.Doc for .NET. Here's how:

  • Using NuGet Package Manager:
    • Open your Visual Studio project.
    • Right-click on the project in the Solution Explorer and select "Manage NuGet Packages."
    • Search for "Spire.Doc" and install the latest version.
  • Manual Installation:
    • Download the Spire.Doc package from the official website.
    • Extract the files and reference the DLLs in your project.

Once installed, you're ready to begin.

Steps for Extracting Images from Word

  • Import Spire.Doc module.
  • Load the Word document.
  • Iterate through sections, paragraphs, and child objects.
  • Identify images and saving them to a specified location.

Using the Code

The following C# code demonstrates how to extract images from a Word document:

  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace ExtractImages
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a Document object
            Document document = new Document();

            // Load the Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Counter for image files
            int index = 0;

            // Loop through each section in the document
            foreach (Section section in document.Sections)
            {
                // Loop through paragraphs in the section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    // Loop through objects in the paragraph
                    foreach (DocumentObject docObject in paragraph.ChildObjects)
                    {
                        // Check if the object is an image
                        if (docObject.DocumentObjectType == DocumentObjectType.Picture)
                        {
                            // Save the image as a PNG file
                            DocPicture picture = docObject as DocPicture;
                            picture.Image.Save(string.Format("output/image_{0}.png", index), System.Drawing.Imaging.ImageFormat.Png);
                            index++;
                        }
                    }
                }
            }

            // Dispose resources
            document.Dispose();
        }
    }
}

The extracted images will be saved in the "output" folder with filenames like image_0.png, image_1.png, etc.

Extract images from Word

Additional Tips & Best Practices

  • Handling Different Image Formats:
    • Convert images to preferred formats (JPEG, BMP) by changing ImageFormat.Png
    • Consider using ImageFormat.Jpeg for smaller file sizes
  • Error Handling:
    • C#
    try {
        // extraction code
    }
    catch (Exception ex) {
        Console.WriteLine($"Error: {ex.Message}");
    }
    
  • Performance Optimization:
    • For large documents, consider using parallel processing
    • Implement progress reporting for user feedback
  • Advanced Extraction Scenarios:
    • Extract images from headers/footers by checking Section.HeadersFooters

Conclusion

Using Spire.Doc in C# simplifies the process of extracting images from Word documents. This approach is efficient and can be integrated into larger document-processing workflows.

Beyond images, Spire.Doc also supports extracting various other elements from Word documents, including:

Whether you're building a document management system or automating report generation, Spire.Doc provides a reliable way to handle Word documents programmatically.

Get a Free License

To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.

Published in Image and Shape

Add Images to Word Documents in .NET

Adding images to Word documents programmatically is a common requirement in document automation. Whether you're generating reports, creating invoices, or building dynamic documents, inserting and customizing images can enhance your document's visual appeal.

In this article, we'll explore how to insert images into Word documents using Spire.Doc for .NET, covering local files, byte arrays, and advanced image customization.

.NET Library for Adding Images to Word

Spire.Doc for .NET is a powerful library that enables developers to create, edit, and manipulate Word documents without Microsoft Office dependencies. It provides straightforward methods to insert and format images in Word files.

Key Features:

  • Insert images from local storage or byte arrays.
  • Adjust image size, rotation, and positioning.
  • Control text wrapping around images.
  • Support for various image formats (PNG, JPG, BMP, etc.).

To get started, downoad Spire.Doc from our offical website and reference the DLLs in your project. Or, you can install it via NuGet through the following command:

PM> Install-Package Spire.Doc

Insert an Imge from Local to Word

The simplest method for inserting images into a Word document is to load them directly from your file system. Using Spire.Doc's AppendPicture() method, you can easily specify the file path of the image. This method automatically detects the image format and embeds it into the document.

using Spire.Doc;
using Spire.Doc.Documents;

namespace InsertImageFromLocal
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Add a section
            Section section = document.AddSection();

            // Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            // Append a picture from the local disk
            paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\MyPic.png");

            // Save the document
            document.SaveToFile("output.docx", FileFormat.Docx);

            // Dispose resources
            document.Dispose();
        }
    }
}

Insert Images to Word in C#

Insert an Image from a Byte Array to Word

In dynamic applications, integrating images from web sources or databases is often essential for enhancing user experience and content relevance.This method downloads images as byte arrays and injecte into the document using a MemoryStream .

By utilizing this technique, developers can dynamically populate documents with up-to-date content, such as logos or product images, directly from online resources or databases.

using Spire.Doc;
using Spire.Doc.Documents;

namespace InsertImageFromByteArray
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            // URL of the image
            string imageUrl = "https://example.com/image.png";

            // Download the image
            byte[] imageBytes;
            using (HttpClient client = new HttpClient())
            {
                imageBytes = await client.GetByteArrayAsync(imageUrl);
            }

            // Create a Document object
            Document document = new Document();

            // Add a section
            Section section = document.AddSection();

            // Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            // Append a picture from the byte array
            using (MemoryStream stream = new MemoryStream(imageBytes))
            {
                paragraph.AppendPicture(stream);
            }

            // Save the document
            document.SaveToFile("output.docx", FileFormat.Docx);

            // Dispose resources
            document.Dispose();
        }
    }
}

Further Customize the Image

Professional documents often demand precise image formatting. Spire.Doc offers extensive controls through the DocPicture class, enabling users to manipulate images effectively.

Key features include resizing to fit layouts, rotating for optimal orientation, and text wrapping options that allow text to flow seamlessly around images. Additionally, users can specify spacing and alignment to position images accurately relative to surrounding content.

// Append an image from disk
DocPicture picture = paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\MyPic.png");

// Resize the image to 70%
picture.SetScale(70f);

// Rotate the image 10 degrees counterclockwise
picture.Rotation = -10;

// Specify top and bottom distance to 3 units
picture.DistanceTop = picture.DistanceBottom = 3;

// Set the text wrapping style around the image
picture.TextWrappingStyle = TextWrappingStyle.TopAndBottom;

// Center align the paragraph containing the image
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center;

Conclusion

Using Spire.Doc for .NET simplifies the process of inserting and customizing images in Word documents. Whether pulling images from local storage or online sources, the library provides flexible options to enhance document presentation.

Get a Free License

To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.

Published in Image and Shape
Page 2 of 2