Skip to content

3.9 Draw Image and Clip it

OgreTransporter edited this page Mar 2, 2020 · 1 revision

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;
}
Clone this wiki locally