Often, text alone can communicate a message, but sometimes graphics are needed. Even when they aren't, text alone can be a bit dull to read. In this article, we'll take a look at incorporating graphics into a PDF document with iTextSharp.
The first thing we'll take a look at is adding existing images into a PDF document. The library supports various images types, each represented by its own class and derived from the Image class, which is abstract. We can import an image using the GetInstance static method of the Image class. This will create an instance of the specified image. There are a number of versions of this method that suit different purposes (for example, creating an image through the image's data), but the easiest one to use accepts a string-the filename of the image to retrieve:
Image logo = Image.GetInstance("aspfreelogo.JPG");
This will return the image aspfreelogo.JPG and will return an instance of the Jpeg class. The image can then be added to the page through Document.Add:
By default, the image is placed on the left side of the page. However, this can be changed through the Alignment property. Instead of placing the image on the left side, you can place it in the center or on the right side:
logo.Alignment = Element.ALIGN_CENTER;
logo.Alignment = Element.ALIGN_RIGHT;
Of course, in some cases, you probably don't want the image occupying a whole chunk of space by itself. Instead, you may want text wrapped around the image. This can be arranged using the Alignment property as well:
logo.Alignment = Image.TEXTWRAP;
In other cases, you may want the image to be behind the text:
logo.Alignment = Image.UNDERLYING;
The above two settings can be combined with the settings for left, center, and right alignment by using the bitwise OR operator. The following line of code will place the image on the right side of the page, with text wrapped around it:
So far, we've been placing the image wherever we happen to be on the current page, just like we'd place a paragraph. However, sometimes it's necessary to place an image at a specific location on the page. The SetAbsolutePosition method can be used to do this. It accepts two float values, which, together, form a coordinate on the current page. This coordinate is the location of the lower left corner of the image. So to place an image an inch from the left of the page and an inch from the bottom, we'd do this:
The image is still added to the page as before, using the Add method.