-
Notifications
You must be signed in to change notification settings - Fork 1
3.9 Draw Image and Clip it
The DrawImage
method is an example of drawing an image. The PdfFileWriter
support drawing images stored in all image files supported by Bitmap
class and Metafile
class. The ImageFormat
class defines all image types. The JPEG image file type is the native image format of the PDF file. If you call the PdfImage
constructor with JPEG file, the program copies the file as is into the PDF file. If you call the PdfImage
constructor with any other type of image file, the program converts it into JPEG file. In order to keep the PDF file size as small as possible, make sure your image file resolution is not unreasonably high.
The PdfImage
class loads the image and calculates maximum size that can fit a given image size in user coordinates and preserve the original aspect ratio. Before drawing the image we create an oval clipping path to clip the image.
// Draw image and clip it
private void DrawImage()
{
// define local image resources
// resolution 96 pixels per inch, image quality 50%
PdfImage Image1 = new PdfImage(Document);
Image1.Resolution = 96.0;
Image1.ImageQuality = 50;
Image1.LoadImage("TestImage.jpg");
// save graphics state
Contents.SaveGraphicsState();
// translate coordinate origin to the center of the picture
Contents.Translate(3.75, 5.0);
// adjust image size and preserve aspect ratio
PdfRectangle NewSize = Image1.ImageSizePosition(1.75, 1.5, ContentAlignment.MiddleCenter);
// clipping path
Contents.DrawOval(NewSize.Left, NewSize.Bottom, NewSize.Width, NewSize.Height, PaintOp.ClipPathEor);
// draw image
Contents.DrawImage(Image1, NewSize.Left, NewSize.Bottom, NewSize.Width, NewSize.Height);
// restore graphics state
Contents.RestoreGraphicsState();
return;
}
This page is a copy from https://www.codeproject.com/Articles/570682/PDF-File-Writer-Csharp-Class-Library by Uzi Granot. The article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL). All rights to the texts and source code remain with Uzi Granot.