Skip to content

Instantly share code, notes, and snippets.

@fileformat-words-gists
Last active December 16, 2023 17:53
Show Gist options
  • Save fileformat-words-gists/1c1eaf2878e5e25717561a3f3cbe43d6 to your computer and use it in GitHub Desktop.
Save fileformat-words-gists/1c1eaf2878e5e25717561a3f3cbe43d6 to your computer and use it in GitHub Desktop.
C# Modify Word Document Images
/// <summary>
/// Loads a Word Document with structured content using
/// <a href="https://www.nuget.org/packages/FileFormat.Words">FileFormat.Words</a>.
/// Gets images from the word document. Decodes image using SkiaSharp and encode to JPG.
/// Resize image to 250(height) and 200(width).
/// Saves the modified Word Document.
/// </summary>
/// <param name="documentDirectory">
/// The directory where the Word Document to load is present and
/// the modified document will be saved (default is root of your project).
/// </param>
/// <param name="filename">
/// The name of the Word Document file to modify (default is "WordImages.docx").
/// </param>
/// <param name="filenameModified">
/// The name of the modified Word Document (default is "ModifiedWordImages.docx").
/// </param>
public void ModifyImagesInWordDocument(string documentDirectory = "../../../",
string filename = "WordImages.docx", string filenameModified = "ModifiedWordImages.docx")
{
try
{
// Load the Word Document
var doc = new FileFormat.Words.Document($"{documentDirectory}/{filename}");
var body = new FileFormat.Words.Body(doc);
foreach (var img in body.Images)
{
var skBitmap = SkiaSharp.SKBitmap.Decode(img.ImageData);
var skImage = SkiaSharp.SKImage.FromBitmap(skBitmap);
var encoded = skImage.Encode(SkiaSharp.SKEncodedImageFormat.Jpeg, 100);
img.ImageData = encoded.ToArray();
img.Height = 250;
img.Width = 200;
doc.Update(img);
}
// Save the modified Word Document
doc.Save($"{documentDirectory}/{filenameModified}");
System.Console.WriteLine($"Word Document {filename} Modified and Saved As {filenameModified}. "+
$"Please check directory: {System.IO.Path.GetFullPath(documentDirectory)}");
}
catch (System.Exception ex)
{
throw new FileFormat.Words.FileFormatException("An error occurred.", ex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment