This project has moved. For the latest updates, please go here.

Is it possible to insert new image into document from memory (i.e., not a physically saved image)?

Jun 30, 2014 at 2:45 PM
Hi,
I am drawing/creating a number of chart images using GDI+, that I need to then insert into a Word document. I would really like to do this without having to first save each image to disk and then insert the image into Word from the specified filepath etc. It seems this is not possible with Word Interop, but is this possible to achieve with DocX?

I tried the following approach, and it doesn't work:
using (DocX document = DocX.
    Load(
        "C:\\..\\..\\ReportTemplate1.dotx")
        )
{
    // Create a new Paragraph.
    Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");

    Bitmap Chart;
    TestChart tChart = new TestChart();
    Chart = tChart.TestImage();

    MemoryStream stream = new MemoryStream();
    Chart.Save(stream,ImageFormat.Jpeg);
    //byte[] byteArray = stream.GetBuffer();

    Novacode.Image img = document.AddImage(stream);
    Picture pic1 = p.InsertPicture(img.Id);

    Picture pic2 = p.AppendPicture(img);

    // Save all changes made to this document.
    document.Save();
}
"TestChart()" generates the image as a Bitmap GDI+. When I get down to
Picture pic1 = p.InsertPicture(img.Id);
I run into trouble, and it will not accept "img" as a Novacode.Image variable.

Any help would be really appreciated about whether this is not possible or what I am doing wrong, as I am very keen to make use of DocX for this piece of work. It looks so much nicer to work with than either Word Interop of Open XML.....!
Jul 3, 2014 at 11:27 AM
Hi Steven,

I'm also interested in how to do this.

I'd not decided how to create the image on the fly, was considering a way to create a SVG format image (but not sure if Word supports that). Will need to experiment...

Robin
Jul 31, 2014 at 11:41 AM
Are you getting the message 'Parameter is not valid'?

If so, this is because when you call the Save() method on Chart, the pointer is at the end of the stream.

Try adding the following line just after Chart.Save( stream, ImageFormat.Jpeg ):
stream.Seek( 0, SeekOrigin.Begin );
Hope this helps.