Working with Images

Aspose.Words allows users to work with images in a very flexible way. In this article, you can explore only some of the possibilities of working with images.

Inserting an Image

DocumentBuilder provides several overloads of the the insert_image 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 insert_image method can use images from different sources:

  • From a file or URL by passing a string parameter
  • From a stream by passing a Stream parameter
  • From a byte array by passing a byte array parameter

For each of the insert_image 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, insert_image
  • Percentage scale or custom size; furthermore, the DocumentBuilder.insert_image method returns a Shape object that was just created and inserted so you can further modify properties of the Shape

Inserting an Inline Image

Pass a single string representing a file that contains the image to insert_image to insert the image into the document as an inline graphic.

The following code example shows how to insert an inline image at the cursor position into a document:

doc = aw.Document()
builder = aw.DocumentBuilder(doc)

builder.insert_image(docs_base.images_dir + "Logo.jpg")

doc.save(docs_base.artifacts_dir+"WorkingWithImages.document_builder_insert_inline_image.doc")

Inserting a Floating (Absolutely Positioned) Image

The following code example shows how to insert a floating image from a file or URL at a specified position and size:

doc = aw.Document()
builder = aw.DocumentBuilder(doc)

builder.insert_image(docs_base.images_dir + "Logo.jpg",
    aw.drawing.RelativeHorizontalPosition.MARGIN,
    100,
    aw.drawing.RelativeVerticalPosition.MARGIN,
    100,
    200,
    100,
    aw.drawing.WrapType.SQUARE)

doc.save(docs_base.artifacts_dir+"WorkingWithImages.document_builder_insert_floating_image.doc")

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:

The following code 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-Python-via-.NET
doc = aw.Document(docs_base.my_dir + "Images.docx")
shapes = doc.get_child_nodes(aw.NodeType.SHAPE, True)
imageIndex = 0
for shape in shapes :
shape = shape.as_shape()
if (shape.has_image) :
imageFileName = f"Image.ExportImages.{imageIndex}_{aw.FileFormatUtil.image_type_to_extension(shape.image_data.image_type)}"
shape.image_data.save(docs_base.artifacts_dir + imageFileName)
imageIndex += 1

How to Insert Barcode on each Page of a Document

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 the move_to_section, move_to_header_footer and insert_image 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-Python-via-.NET
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
# The number of pages the document should have
numPages = 4
# The document starts with one section, insert the barcode into this existing section
self.insert_barcode_into_footer(builder, doc.first_section, aw.HeaderFooterType.FOOTER_PRIMARY)
for i in range(1, numPages) :
# Clone the first section and add it into the end of the document
cloneSection = doc.first_section.clone(False).as_section()
cloneSection.page_setup.section_start = aw.SectionStart.NEW_PAGE
doc.append_child(cloneSection)
# Insert the barcode and other information into the footer of the section
self.insert_barcode_into_footer(builder, cloneSection, aw.HeaderFooterType.FOOTER_PRIMARY)
# Save the document as a PDF to disk
# You can also save this directly to a stream
doc.save(docs_base.artifacts_dir + "InsertBarcodeImage.docx")
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
@staticmethod
def insert_barcode_into_footer(builder : aw.DocumentBuilder, section : aw.Section, footerType : aw.HeaderFooterType) :
# Move to the footer type in the specific section.
builder.move_to_section(section.document.index_of(section))
builder.move_to_header_footer(footerType)
# Insert the barcode, then move to the next line and insert the ID along with the page number.
# Use pageId if you need to insert a different barcode on each page. 0 = First page, 1 = Second page etc.
builder.insert_image(docs_base.images_dir + "Barcode.png")
builder.writeln()
builder.write("1234567890")
builder.insert_field("PAGE")
# Create a right-aligned tab at the right margin.
tabPos = section.page_setup.page_width - section.page_setup.right_margin - section.page_setup.left_margin
builder.current_paragraph.paragraph_format.tab_stops.add(aw.TabStop(tabPos, aw.TabAlignment.RIGHT, aw.TabLeader.NONE))
# Move to the right-hand side of the page and insert the page and page total.
builder.write(aw.ControlChar.TAB)
builder.insert_field("PAGE")
builder.write(" of ")
builder.insert_field("NUMPAGES")

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 aspect_ratio_locked. 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.

The following code example shows how to work with aspect ratio:

doc = aw.Document()
builder = aw.DocumentBuilder(doc)

shape = builder.insert_image(docs_base.images_dir + "Logo.jpg")
shape.aspect_ratio_locked = False

doc.save(docs_base.artifacts_dir+"WorkingWithImages.set_aspect_ratio_locked.doc")

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 the bounds_in_points property.

The following code example shows how to use this property:

doc = aw.Document()
builder = aw.DocumentBuilder(doc)

shape = builder.insert_image(docs_base.images_dir + "Logo.jpg")
shape.aspect_ratio_locked = False

print("\nGets the actual bounds of the shape in points.")
rect = shape.get_shape_renderer().bounds_in_points
print(f"{rect.x}, {rect.y}, {rect.width}, {rect.height}")

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.

The following code example shows how to achieve this using Aspose.Words API:

# The path to the documents directory.
inputPath = docs_base.images_dir + "Logo.jpg"
outputPath = docs_base.artifacts_dir + "cropped_logo.jpg"

self.crop_image(inputPath,outputPath, 100, 90, 200, 200)
@staticmethod
def crop_image(inPath : str, outPath : str, left : int, top : int, width : int, height : int) :
    
    doc = aw.Document();
    builder = aw.DocumentBuilder(doc)
    
    croppedImage = builder.insert_image(inPath)
    
    src_width_points = croppedImage.width
    src_height_points = croppedImage.height
    
    croppedImage.width = aw.ConvertUtil.pixel_to_point(width)
    croppedImage.height = aw.ConvertUtil.pixel_to_point(height)
    
    widthRatio = croppedImage.width / src_width_points
    heightRatio = croppedImage.height / src_height_points
    
    if (widthRatio< 1) :
        croppedImage.image_data.crop_right = 1 - widthRatio
    
    if (heightRatio< 1) :
        croppedImage.image_data.crop_bottom = 1 - heightRatio
    
    leftToWidth = aw.ConvertUtil.pixel_to_point(left) / src_width_points
    topToHeight = aw.ConvertUtil.pixel_to_point(top) / src_height_points
    
    croppedImage.image_data.crop_left = leftToWidth
    croppedImage.image_data.crop_right = croppedImage.image_data.crop_right - leftToWidth
    
    croppedImage.image_data.crop_top = topToHeight
    croppedImage.image_data.crop_bottom = croppedImage.image_data.crop_bottom - topToHeight
    
    croppedImage.get_shape_renderer().save(outPath, aw.saving.ImageSaveOptions(aw.SaveFormat.JPEG))

Saving 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 shows 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-Python-via-.NET
doc = aw.Document(docs_base.my_dir + "Document.docx")
saveOptions = aw.saving.RtfSaveOptions()
saveOptions.save_images_as_wmf = True
doc.save(docs_base.artifacts_dir + "WorkingWithRtfSaveOptions.saving_images_as_wmf.rtf", saveOptions)