Skip to content

Instantly share code, notes, and snippets.

@fileformat-words-gists
Last active December 16, 2023 17:51
Show Gist options
  • Save fileformat-words-gists/cae0acdf7e5ef5f177402e4742aadc3d to your computer and use it in GitHub Desktop.
Save fileformat-words-gists/cae0acdf7e5ef5f177402e4742aadc3d to your computer and use it in GitHub Desktop.
C# Create Word Document Images
/// <summary>
/// Creates a new Word Document with structured content using
/// <a href="https://www.nuget.org/packages/FileFormat.Words">FileFormat.Words</a>.
/// Loads images from the specified diretory and decodes using SkiaSharp.
/// Creates a word document, appends loaded images and then saves the word document.
/// </summary>
/// <param name="documentDirectory">
/// The directory where the Word Document will be saved (default is root of your project).
/// </param>
/// <param name="imageDirectory">
/// The directory from where the images will be loaded (default is 'Images' directory at root of your project).
/// </param>
/// <param name="filename">
/// The name of the Word Document file (default is "WordImages.docx").
/// </param>
public void CreateWordDocumentWithImages(string documentDirectory = "../../../",
string imageDirectory = "../../../Images",
string filename = "WordImages.docx")
{
try
{
// Initialize a new word document with the default template
var doc = new FileFormat.Words.Document();
// Initialize the body with the new document
var body = new FileFormat.Words.Body(doc);
// Load images from the specified directory
var imageFiles = System.IO.Directory.GetFiles(imageDirectory);
foreach(var imageFile in imageFiles)
{
// Decode the image with SkiaSharp
using (var skBMP = SkiaSharp.SKBitmap.Decode(imageFile))
{
using (var skIMG = SkiaSharp.SKImage.FromBitmap(skBMP))
{
var encoded = skIMG.Encode(SkiaSharp.SKEncodedImageFormat.Png, 100);
// Initialize the word document image element
var img = new FileFormat.Words.IElements.Image();
// Load data for the word document image element
img.ImageData = encoded.ToArray();
img.Height = 350;
img.Width = 300;
// Append image element to the word document
body.AppendChild(img);
System.Console.WriteLine($"Image {System.IO.Path.GetFullPath(imageFile)} "+
$"added to the word document.");
}
}
}
// Save the newly created Word Document.
doc.Save($"{documentDirectory}/{filename}");
System.Console.WriteLine($"Word Document {filename} Created. "+
$"Please check directory: {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