Working with Images
How to Insert an Image
DocumentBuilder provides several overloads of the DocumentBuilder.InsertImage method that allows you to insert an inline or floating image. If the image is an EMF or WMF metafile, it will be inserted into the document in metafile format. All other images will be stored in PNG format. The DocumentBuilder.InsertImage method can use images from different sources:
- From a file or URL by passing a string parameter DocumentBuilder.InsertImage.
- From a stream by passing a Stream parameter DocumentBuilder.InsertImage.
- From an Image object by passing an Image parameter DocumentBuilder.InsertImage.
- From a byte array by passing a byte array parameter DocumentBuilder.InsertImage. For each of the DocumentBuilder.InsertImage methods, there are further overloads which allow you to insert an image with the following options:
- Inline or floating at a specific position, for example, DocumentBuilder.InsertImage.
- Percentage scale or custom size, for example, DocumentBuilder.InsertImage. Furthermore, the DocumentBuilder.InsertImage method returns a Shape object that was just created and inserted so you can further modify properties of the Shape.
How to Insert an Inline Image
Pass a single string representing a file that contains the image to DocumentBuilder.InsertImage to insert the image into the document as an inline graphic. Below example shows how to insert an inline image at the cursor position into a document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.InsertImage(dataDir + "Watermark.png"); | |
dataDir = dataDir + "DocumentBuilderInsertInlineImage_out.doc"; | |
doc.Save(dataDir); |
How to Insert a Floating Image
This example inserts a floating image from a file or URL at a specified position and size.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.InsertImage(dataDir + "Watermark.png", | |
RelativeHorizontalPosition.Margin, | |
100, | |
RelativeVerticalPosition.Margin, | |
100, | |
200, | |
100, | |
WrapType.Square); | |
dataDir = dataDir + "DocumentBuilderInsertFloatingImage_out.doc"; | |
doc.Save(dataDir); |
How to Extract Images from a Document
All images are stored inside Shape nodes in a Document. To extract all images or images having specific type from the document, follow these steps:
- Use the Document.GetChildNodes method to select all Shape nodes.
- Iterate through resulting node collections.
- Check the Shape.HasImage boolean property.
- Extract image data using the Shape.ImageData property.
- Save image data to a file.
Below example shows how to extract images from a document and save them as files. You can download the template file of this example from here.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_WorkingWithImages(); | |
Document doc = new Document(dataDir + "Image.SampleImages.doc"); | |
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true); | |
int imageIndex = 0; | |
foreach (Shape shape in shapes) | |
{ | |
if (shape.HasImage) | |
{ | |
string imageFileName = string.Format( | |
"Image.ExportImages.{0}_out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType)); | |
shape.ImageData.Save(dataDir + imageFileName); | |
imageIndex++; | |
} | |
} |
How to Insert Barcode on each Document Page
This example demonstrates you to add the same or different barcodes on all or specific pages of a Word document. There is no direct way to add barcodes on all pages of a document but you can use DocumentBuilder.MoveToSection, DocumentBuilder.MoveToHeaderFooter and DocumentBuilder.InsertImage methods to move to any section or headers/footers and insert the barcode images as you can see in the following code. The following code example Inserts a barcode image on each page of a document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_WorkingWithImages(); | |
// Create a blank documenet. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// The number of pages the document should have. | |
int numPages = 4; | |
// The document starts with one section, insert the barcode into this existing section. | |
InsertBarcodeIntoFooter(builder, doc.FirstSection, 1, HeaderFooterType.FooterPrimary); | |
for (int i = 1; i < numPages; i++) | |
{ | |
// Clone the first section and add it into the end of the document. | |
Section cloneSection = (Section)doc.FirstSection.Clone(false); | |
cloneSection.PageSetup.SectionStart = SectionStart.NewPage; | |
doc.AppendChild(cloneSection); | |
// Insert the barcode and other information into the footer of the section. | |
InsertBarcodeIntoFooter(builder, cloneSection, i, HeaderFooterType.FooterPrimary); | |
} | |
dataDir = dataDir + "Document_out.docx"; | |
// Save the document as a PDF to disk. You can also save this directly to a stream. | |
doc.Save(dataDir); |
Lock Aspect Ratio of Image
The aspect ratio of a geometric shape is the ratio of its sizes in different dimensions. You can lock the aspect ratio of the image using Shape.AspectRatioLocked. The default value of the shape’s aspect ratio depends on the ShapeType. It is true for ShapeType.Image and false for other shape types.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
var shape = builder.InsertImage(dataDir + "Test.png"); | |
shape.AspectRatioLocked = false; | |
dataDir = dataDir + "Shape_AspectRatioLocked_out.doc"; | |
// Save the document to disk. | |
doc.Save(dataDir); |
How to Get Actual Bounds of Shape in Points
If you want the actual bounding box of the shape as rendered on the page, you can achieve this by using NodeRendererBase.BoundsInPoints property. The following code example demonstrates how to use this property.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
var shape = builder.InsertImage(dataDir + "Test.png"); | |
shape.AspectRatioLocked = false; | |
Console.Write("\nGets the actual bounds of the shape in points."); | |
Console.WriteLine(shape.GetShapeRenderer().BoundsInPoints); |
Crop Images
The cropping of an image usually refers to the removal of the unwanted outer parts of an image to help improve the framing. It is also used for the removal of some of the portions of an image to increase the focus on a particular area. This can be achieved using Aspose.Words API as demonstrated in the example given below.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_WorkingWithImages(); | |
string inputPath = dataDir + "ch63_Fig0013.jpg"; | |
string outputPath = dataDir + "cropped-1.jpg"; | |
CropImage(inputPath,outputPath, 124, 90, 570, 571); |
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
public static void CropImage(string inPath, string outPath, int left, int top,int width, int height) | |
{ | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Image img = Image.FromFile(inPath); | |
int effectiveWidth = img.Width - width; | |
int effectiveHeight = img.Height - height; | |
Shape croppedImage = builder.InsertImage(img, | |
ConvertUtil.PixelToPoint(img.Width - effectiveWidth), | |
ConvertUtil.PixelToPoint(img.Height - effectiveHeight)); | |
double widthRatio = croppedImage.Width / ConvertUtil.PixelToPoint(img.Width); | |
double heightRatio = croppedImage.Height / ConvertUtil.PixelToPoint(img.Height); | |
if (widthRatio< 1) | |
croppedImage.ImageData.CropRight = 1 - widthRatio; | |
if (heightRatio< 1) | |
croppedImage.ImageData.CropBottom = 1 - heightRatio; | |
float leftToWidth = (float)left / img.Width; | |
float topToHeight = (float)top / img.Height; | |
croppedImage.ImageData.CropLeft = leftToWidth; | |
croppedImage.ImageData.CropRight = croppedImage.ImageData.CropRight - leftToWidth; | |
croppedImage.ImageData.CropTop = topToHeight; | |
croppedImage.ImageData.CropBottom = croppedImage.ImageData.CropBottom - topToHeight; | |
croppedImage.GetShapeRenderer().Save(outPath, new ImageSaveOptions(SaveFormat.Jpeg)); | |
} |
Save Images as WMF
Aspose.Words provides functionality to save all the available images in a document to WMF format while converting DOCX to RTF. The following code example demonstrates how to save images as WMF with RTF save options.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
string fileName = "TestFile.doc"; | |
Document doc = new Document(dataDir + fileName); | |
RtfSaveOptions saveOpts = new RtfSaveOptions(); | |
saveOpts.SaveImagesAsWmf = true; | |
doc.Save(dataDir + "output.rtf", saveOpts); |