PDF for WPF and Silverlight Overview > Features: PDF for WPF and Silverlight > Adding Images |
Adding images to PDF for WPF documents is also easy, all the work is done by the C1PdfDocument.DrawImage method.
C1PdfDocument.DrawImage draws a given image at a specified location and has parameters that provide control over the image alignment and scaling. In the following example, the image is center-aligned within the rectangle and scaled to keep the aspect ratio. The sample declares a C1PdfDocument class called 'pdf' and calls method for drawing image.
This code is used to draw the same image as follows:
VB |
Copy Code
|
---|---|
Dim rect As Rect = pdf.PageRectangle rect.Inflate(-150, -150) Dim fs As Stream = File.Open("..\..\image.jpg", FileMode.Open) ' load image into writeable bitmap Dim bi As New BitmapImage() bi.BeginInit() bi.StreamSource = fs bi.EndInit() Dim wb = New WriteableBitmap(bi) ' align image on page preserving aspect ratio pdf.DrawImage(wb, rect, ContentAlignment.MiddleCenter, Stretch.Uniform) |
C# |
Copy Code
|
---|---|
Rect rect = pdf.PageRectangle; rect.Inflate(-150, -150); Stream fs = File.Open(@"..\..\image.jpg", FileMode.Open); // load image into writeable bitmap BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = fs; bi.EndInit(); var wb = new WriteableBitmap(bi); // align image on page preserving aspect ratio pdf.DrawImage(wb, rect, ContentAlignment.MiddleCenter, Stretch.Uniform); |
Rect rect = pdf.PageRectangle();
rect.Inflate(-72, -72);
// Stretch image to fill the rectangle.
pdf.DrawImage(pictureBox1.Image, rect);
// Center image within the rectangle, scale keeping aspect ratio.
pdf.DrawImage(pictureBox1.Image, rect, ContentAlignment.MiddleCenter, C1.WPF.Pdf.ImageSizeModeEnum.Scale);
// Render the image to the top left corner of the rectangle.
pdf.DrawImage(pictureBox1.Image, rect, ContentAlignment.TopLeft, 1.C1Pdf.ImageSizeModeEnum.Clip);
The PDF document will look similar to this:
Notice that you can render any regular .NET Image object, including Metafiles. Metafiles are not converted into bitmaps; they are played into the document and thus retain the best possible resolution. If you want to add charts or technical drawings to your PDF document, Metafiles are better than bitmap images.
Bitmap images are managed automatically by PDF for WPF. If you render the same image several times (in a page header for example), only one copy of the image is saved into the PDF file.