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.
Images don't have to be added to the document as-is. Sometimes they will need to be altered or transformed in some way. The library provides a few ways to transform images. We'll take a look at two of them here.
One of the most basic ways to manipulate an image is to rotate it. Rotation is possible with iTextSharp using two properties: Rotation and RotationDegrees. The first property can be used to rotate the image by an angle in radians. For example, an image could be rotated a quarter-turn counterclockwise like this:
logo.Rotation = (float)Math.PI / 2;
Of course, most people will be more comfortable using degrees. The RotationDegrees property can be used to rotate an image by an angle in degrees. The same quarter-turn could be done using RotationDegrees like this:
logo.RotationDegrees = 90;
Images can also be resized, or scaled, using iTextSharp. There are three ways that an image can be scaled. The first is to scale an image to a certain height, width, or both. The ScaleAbsolute method can be used to give the image both a new height and a new width. To make an image 72 points tall and 36 points wide, we'd do this:
logo.ScaleAbsolute(36, 72);
The height or width of an image can be modified using the ScaleAbsoluteHeight and ScaleAbsoluteWidth methods:
logo.ScaleAbsoluteHeight(72);
logo.ScaleAbsoluteWidth(72);
If you're not careful, though, scaling an image to a specific height or width can distort the image. The ScalePercent method can remedy this. We can pass it a percentage, which will be used to scale the image. To make the image half of its original size, we'd do this:
logo.ScalePercent(50);
Alternatively, the height and the width can be scaled separately. To make the image half as wide, but just as tall, we'd do this:
logo.ScalePercent(50, 100);
As you can see, the first parameter is the percentage to scale the width by, and the second is the percentage to scale the height.
The third way to scale an image is to scale it to fit within a given rectangle using the ScaleToFit method. This accepts a width and a height, just like ScaleAbsolute, but it will not distort the image. The image will be scaled to fit within the rectangle but won't necessarily fill up the rectangle. So, if the original image is a square, and we use ScaleToFit with 72 as the width and 100 as the height, it will end up with both a width and a height of 72:
logo.ScaleToFit(72, 100);
The new dimensions can be checked with the ScaledWidth and ScaledHeight properties.