Note: Code samples have been updated to work with DocX version 184.108.40.206.
Lots of people emailed me asking me to add support for Images in DocX. So I did. Version 220.127.116.11 which can be downloaded from here adds basic support for Images and Pictures.
Images and Pictures? Are they not the same thing you might ask? No they are not! You can think of a Picture as a customized view of an Image. Once you have added Images to a docx file.
You can then add multiple customized Pictures of those Images into Paragraphs. You can do all sorts of interesting customizations with these Pictures before inserting them into Paragraphs. At the moment docx supports the following Picture customizations;
Rotations and transformations
Time for an example using DocX; below is a file entitled Example.docx.
The following code adds the Image Donkey.jpg into this file, it then creates two Pictures using this Image and inserts them into the last Paragraph.// Create a .docx file
using (DocX document = DocX.Create(@"Example.docx"))
// Add an Image to the docx file
Novacode.Image img = document.AddImage(@"Donkey.jpg");
// Insert an emptyParagraph into this document.
Paragraph p = document.InsertParagraph("", false);
Picture pic1 = p.InsertPicture(img.Id, "Donkey", "Taken on Omey island");
// Set the Picture pic1’s shape
// Rotate the Picture pic1 clockwise by 30 degrees
pic1.Rotation = 30;
// Create a Picture. A Picture is a customized view of an Image
Picture pic2 = p.InsertPicture(img.Id, "Donkey", "Taken on Omey island");
// Set the Picture pic2’s shape
// Flip the Picture pic2 horizontally
pic2.FlipHorizontal = true;
// Save the docx file
}// Release this document from memory.
Figure 1.1 – Example.docx after code execution
Another interesting thing that you could do would be to apply an operation to every Picture in a document. The below snippet would rotate every Picture in a document clockwise by 30 degrees.
// Load the document that you want to manipulateIf you would like to send me feedback on DocX, or if you would like to make a suggestion for the next feature I implement, please email me at email@example.com.
using (DocX document = DocX.Load(@"Test.docx"))
// Loop through each Paragraph
foreach (Paragraph p in document.Paragraphs)
// Loop through each Picture in this Paragraph
foreach (Picture pi in p.Pictures)
// Rotate this picture clockwise by 30 degrees
pi.Rotation = 30;
// Save the document
}// Release this document from memory