Import Images through MemoryStream
Hey James, so I decided to move our Conversation into here so other people may also profit from the outcome. To shorten it up a quick sumary: My goal is to get Images from Code into the XML. Right now I am saving them as files and load them in the XML as its explained in the lessons. This is not the perfect approach for me as I would prefer to do it over a MemoryStream. Not beeing able to figure it out by myself I asked James for his support and got this suggestion:
In MigraDoc it's just a matter of converting the image's byte data to a base64 string, prefixing it with "base64:" and putting it into the image name. That should do the trick in MigraDocXml too...I've only used it a few times myself.
If you're passing the image in as a memory stream on your model object, then you'll need to do a little bit of work to get the memory stream into base64 text.
The first option is to add a method or getter on your model which the MigraDocXML code can call to do the conversion into base64. The other approach, especially if you don't have full authorship over the object being passed in, would be to add your own custom EvalScript function (again, definitely need to update lessons to show how this is done):
private string MemoryStreamToBase64(object[] args) { if (args.Length != 1 || !(args[0] is MemoryStream)) throw new Exception("MemoryStreamToBase64 expects a MemoryStream object...duh!"); var memStr = args[0] as MemoryStream; var bytes = memStr.ToArray(); return Convert.ToBase64String(bytes); }
Something like this, not had a chance to test, but looks about right.
Then in the bit where you're calling the PdfXmlReader, just change it to this:
var reader = new PdfXmlReader(LayoutFile); reader.ScriptRunner = new EvalScript.Runner(); reader.ScriptRunner.Evaluator.Functions["MemoryStreamToBase64"] = MemoryStreamToBase64;
In your xml code, you could then do something like:
<Image Name="base64:{MemoryStreamToBase64(model.ImageStream)}"/>
This solution doesn't yet work for me as reader.ScriptRunner
is read only.
Unfortunately I neither wasn't able to find anything helpful at EvalScript
Best Regards, Despot Bitschnau