Images
Version 6.1.0
In this article
- Images from files
- Fileless images
- (This article is under construction)
How to format images is not yet described here
This article describes how images can be used with MigraDoc. MigraDoc can read them directly from files or you can pass byte arrays to MigraDoc using the base64 pseudo-protocol described here.
This article is under construction. How to format images is not yet described here. Maybe, you find some help in Grammar by Example.
Images from files
MigraDoc can be used to create documents and these documents can persist in text files in the MDDDL. The design of MDDDL supports filenames, but was not prepared to support embedding binary image data in MDDDL files.
var document = new Document();
var img = document.LastSection.AddImage("sample.jpg");
Working directory
When rendering a document, you can set the WorkingDirectory in your instance of the PdfDocumentRenderer or RtfDocumentRenderer. Relative image file names will be resolved starting from that WorkingDirectory.
Fileless images
To support images "in memory" and in a file, MigraDoc uses a little trick and allows the binary image data to be passed in a BASE64-encoded string that holds the image data where a filename is expected. MigraDoc uses the "base64" pseudo-protocol to support this.
To convert a byte array containing the image data to a string in the base64 protocol, use code like this:
static string MigraDocFilenameFromByteArray(byte[] image)
{
return "base64:" +
Convert.ToBase64String(image);
}
If images were added to your application using the Build Action "Embedded Resource", you can use code like this to get the byte array from the resource:
static byte[] LoadImage(string name)
{
var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(name))
{
if (stream == null)
throw new ArgumentException("No resource with name " + name);
int count = (int)stream.Length;
byte[] data = new byte[count];
stream.Read(data, 0, count);
return data;
}
}
And here we see both routines working hand in hand to add an image from a resource to a MigraDoc document:
byte[] image = LoadImage("ImageFromResource.images.Color8A.bmp");
string imageFilename = MigraDocFilenameFromByteArray(image);
Document document = new Document();
Section section = document.AddSection();
section.AddImage(imageFilename);