Free Support Forum - aspose.com

Word: InsertImage from Memory w/DocBuilder

In testing aspose.Word, I'm attempting to insert an image via memory using document builder. The only examples I've found on the forum are using the Merge events. I found the following code for aspose.pdf, which looks similar. Roman, can you give me an idea of how the same PDF code is applied to aspose.Word by replacing the snippet relating to inserting into the PDF?

Thank you in advance!

Original example:

Dim chart As Chart = New Chart()
chart.SmoothingMode = SmoothingMode.HighQuality

Dim s As ASeries = New ASeries()
s.ChartType = ChartType.Bar
s.DataPoints.Add(1)
s.DataPoints.Add(2)
s.DataPoints.Add(3)
chart.NSeries.Add(s)

Dim bm As Bitmap = chart.Save()
Dim mstream As System.IO.MemoryStream = New System.IO.MemoryStream()
bm.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp)
Dim reader As System.IO.BinaryReader = New System.IO.BinaryReader(mstream)


'-------------------------------------------Start: PDF Version
Dim pdf1 As Pdf = New Pdf()

Dim sec1 As Section = pdf1.Sections.Add()

Dim image1 As Aspose.Pdf.Image = New Aspose.Pdf.Image(sec1)
sec1.Paragraphs.Add(image1)

image1.ImageInfo.ImageFileType = ImageFileType.MemoryBmp
image1.ImageInfo.OpenType = ImageOpenType.Memory
image1.ImageScale = 0.5F
mstream.Position = 0
image1.ImageInfo.MemoryData = reader.ReadBytes(CType(mstream.Length, Integer))

bm.Dispose()
pdf1.Save("Chart.pdf")
'-------------------------------------------End: PDF Version

I think it is much simpler with Aspose.Word in this area.

DocumentBuilder.InsertImage takes a .NET Image object. It is an image in memory basically. Read a bit more documentation about the Image class, it could help.

You can create an image by loading it from file or from stream using Image.FromFile or Image.FromStream and that pass that image to DocumentBuilder.InsertImage.

If you have a byte array that contains an image, you need to create a MemoryStream on that byte array and then call Image.FromStream.

If you have a stream already (any stream), just call Image.FromFile and pass that image to DocumentBuilder. Note, you might need to seek the stream position to the beginning before loading an image from the stream.

If you want to insert an image during mail merge in an image field event handler, you have three options: to return a file name, an Image object or a stream that contains the image by setting e.ImageFileName, e.Image or e.ImageStream property appropriately.