Images
Version 6.1.0
In this article
- Images from files
- Working directory & image path
- Fileless images
- Sizing & positioning
- Inline images
- Line & fill format
This article describes how images can be used with MigraDoc.
Images from files
The easiest way to include an image is to add it specifying its filename. Simply call the AddImage function, for example at the section:
// Load image from relative path.
section.AddImage("MigraDoc-landscape.png");
See full FromFile sample in PDFsharp.Sample repository. Show resulting PDF
Additionally, there are also some other objects you can add images to. You can call an AddImage method for example inside of text elements like paragraphs and formatted texts (see Text). You can further call it for a hyperlink (see Hyperlinks), a header or footer (see Headers & footers) or a table cell (see Tables).
Working directory & image path
For images with relative paths the ImagePath property of the Document instance and the WorkingDirectory property in your instance of the PdfDocumentRenderer or RtfDocumentRenderer (see Document / Rendering for more information) control where the image is searched.
The image is first searched at path set with the ImagePath property. If that also contains a relative path, a root directory is preceded. This root directory is taken from the WorkingDirectory property. If that is not set, the working directory of the application is used instead. If the image is not found there or the ImagePath property is not set, it is searched directly in this root directory.
In the following example, images shall be loaded from "../../../../../../../../../assets/migradoc/images". Furthermore, "../../.." shall be the folder to create the document at, so WorkingDirectory is set to that value and ImagePath is set to "../../../../../../assets/migradoc/images" (without the first three upward moves).
// Set the image path.
document.ImagePath = "../../../../../../assets/migradoc/images";
…
// Load image from relative path.
// As both WorkingDirectory and ImagePath are set here, it is tried at
// "../../.." + "/" + "../../../../../../assets/migradoc/images"
// and it would be further tried at "../../.." if it was not there.
section.AddImage("MigraDoc-landscape.png");
…
// Set the working directory, which will be the root for images with relative paths
// and for the document saving operations.
pdfRenderer.WorkingDirectory = "../../..";
See full WorkingDirectoryAndImagePath sample in PDFsharp.Sample repository. Show resulting PDF
Fileless images
MigraDoc was developed together with the MigraDoc Document Description Language (MDDDL). MDDDL is a text-based serialization of a MigraDoc document. The design of MDDDL supports filenames but was not prepared to support embedding binary image data in MDDDL files.
To support images "in memory", 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);
}
See full FromByteArray sample in PDFsharp.Sample repository. Show resulting PDF
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);
Sizing & positioning
The Image class is derived from Shape. How to resize and position a shape is described at Formats / Sizing & positioning.
However, for resizing images, there are some more possibilities.
Additionally to the Width and Height properties, there is a ScaleWidth and a ScaleHeight property. Using those properties, you can specify a factor to be multiplied with the Width or Height value.
image.ScaleWidth = 2;
image.ScaleHeight = 0.5;
See full Resizing sample in PDFsharp.Sample repository. Show resulting PDF
The LockAspectRatio property defines if the aspect ratio of the image shall be retained. The default value is true, so if you only set the width or the height of an image, the other dimension is increased or decreased proportionally. However, if you set both the with and the height of an image, the LockAspectRatio value is ignored. If you set LockAspectRatio to false, setting the width or the height only will stretch the image.
image.LockAspectRatio = false;
image.ScaleHeight = 0.5;
See full Resizing sample in PDFsharp.Sample repository. Show resulting PDF
You can also specify the resolution of an image. By default, images are inserted at a resolution of 72 dpi. If you set the Resolution property to another value, the initial size of the image will change:
image.Resolution = 300;
See full Resizing sample in PDFsharp.Sample repository. Show resulting PDF
By default, image interpolation is enabled. Especially if an image is enlarged or of a bad resolution, this will improve its appearance. If you prefer clear pixel edges for an image, you should set the Interpolate property to false:
image.Interpolate = false;
See full Resizing sample in PDFsharp.Sample repository. Show resulting PDF
Inline images
In contrast to other shapes like text frames and charts, images can appear within paragraphs. Inline images are handled like a word within a paragraph. This implies the following consequences:
- The bottom of an inline image is aligned to the text base line.
- The image height is taken into account when rendering the line containing it.
- All image attributes that deal with its position are ignored.
- The image position can be influenced by tab stops.
You can add an inline image by calling the AddImage method for a paragraph or formatted text:
paragraph.AddImage("MigraDoc-80x80.png");
See full InlineImages sample in PDFsharp.Sample repository. Show resulting PDF
The sample file shows how to insert an image as a bullet and how to align it with a tab stop. As position attributes are ignored for inline images, the distance properties of the WrapFormat class won’t have an effect (see Formats / Sizing & positioning for more information). To work around this, the sample file also shows how to increase the distance using no-break spaces.
Line & fill format
Line and fill format are not explained in this article, as not only images can be formatted using them. For information about how the format of borders is changed, see Formats / Borders & line format. For information about how to change the background color using a shading, see Formats / Shading & fill format.
For images with transparency, the fill format will shine through in those areas.