Login

Adding Images With iTextSharp

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.

Adding Images

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:

doc.Add(logo);

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:

logo.Alignment = Element.ALIGN_RIGHT | Image.TEXTWRAP;

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:

logo.SetAbsolutePosition(72, 72);

The image is still added to the page as before, using the Add method.

{mospagebreak title=Adding padding and a border}

Sometimes, it’s necessary to put some space between the image and other content. This is done just as with a Paragraph. Like a Paragraph, an Image has IndentationLeft, IndentationRight, SpacingBefore, and SpacingAfter properties that can be used to pad the image. Here, we create half an inch of padding on all sides:

logo.IndentationLeft = 36;

logo.IndentationRight = 36;

logo.SpacingBefore = 36;

logo.SpacingAfter = 36;

Note that adding padding will have no effect if there’s nothing in the direction of the padding. For example, adding padding to the right of an image that’s aligned to the right won’t add extra space.

Another technique that helps to set an image apart is adding a border to it. There are at least two steps involved in adding a border around an image. The first step is to set the Border property to specify what sides of the image will need a border. The binary OR operator can be used to combine Image.LEFT_BORDER, Image.RIGHT_BORDER, Image.TOP_BORDER, and Image_BOTTOM_BORDER to create the appropriate border. Here, we create a border around all sides of an image:

logo.Border = Image.LEFT_BORDER | Image.TOP_BORDER |

Image.RIGHT_BORDER | Image.BOTTOM_BORDER;

The next step is to set the width of the border in points. Here, we set the border to be one point wide:

logo.BorderWidth = 1;

This will create a black border around all sides of the image. However, it’s possible to specify a width for each side individually:

logo.BorderWidthLeft = 1;

logo.BorderWidthRight = 1;

logo.BorderWidthTop = 1;

logo.BorderWidthBottom = 1;

These first two steps will create a black border around the image. Of course, black may not work in all situations, so it’s possible to specify another color. Below, a border is set to red:

logo.BorderColor = Color.RED;

This will make the entire border red. As with width, though, each side can be colored differently:

logo.BorderColorLeft = Color.LIGHT_GRAY;

logo.BorderColorTop = Color.GRAY;

logo.BorderColorRight = Color.DARK_GRAY;

logo.BorderColorBottom = Color.BLACK;

{mospagebreak title=Manipulating an Image}

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.

{mospagebreak title=An example}

Let’s put together what we’ve covered so far in a short example. In this example, we’ll create something that looks like this:

Note that this image is scaled down.

We’ll use the ASP Free logo. Download it and place it in a directory in which the example will execute (the output directory of the Visual Studio project-you can add it to the project and set it to be copied to the output directory in the Properties Window):

In order to achieve the result we want, we’ll need to create three instances of the image. All three will have to be rotated and will need borders. Two will need to be positioned manually and will be located beneath the text. The third will have text wrapped around it and will be positioned automatically. It will also be enlarged.

using System;

using System.IO;

using iTextSharp.text;

using iTextSharp.text.pdf;

classImages1

{

publicstaticvoid Main()

{

string text = "This is a paragraph. It is represted" +

" by a Paragraph object in the iTextSharp " +

"library. Here, we’re creating paragraphs with " +

"various styles in order to test out iTextSharp." +

" This paragraph will take up multiple lines " +

"and allow for a more complete example.";

Document doc = newDocument(PageSize.LETTER,

72, 72, 72, 72);

PdfWriter.GetInstance(doc,

newFileStream("images1.pdf", FileMode.Create));

doc.Open();

// Get instances of the images

string imagePath = Path.Combine(

System.Environment.CurrentDirectory,

"aspfreelogo.JPG");

Image logoLeft = Image.GetInstance(imagePath);

Image logoBottom = Image.GetInstance(imagePath);

Image logoRight = Image.GetInstance(imagePath);

// Add some text

doc.Add(newParagraph(text));

doc.Add(newParagraph(text));

// Add the top-left image

logoLeft.Alignment = Image.UNDERLYING;

logoLeft.Rotation = (float)Math.PI / -3;

logoLeft.Border = Image.RIGHT_BORDER;

logoLeft.BorderWidth = 1;

logoLeft.BorderColor = Color.RED;

logoLeft.SetAbsolutePosition(72, 72 * 9);

doc.Add(logoLeft);

// Add the top-right image

logoRight.Alignment = Image.UNDERLYING;

logoRight.Rotation = (float)Math.PI / 3;

logoRight.Border = Image.LEFT_BORDER;

logoRight.BorderWidth = 1;

logoRight.BorderColor = Color.BLUE;

logoRight.SetAbsolutePosition(72 * 4, 72 * 9);

doc.Add(logoRight);

// Add the bottom-left image

// (using degrees to rotate it!)

logoBottom.ScalePercent(150);

logoBottom.Alignment = Image.TEXTWRAP;

logoBottom.RotationDegrees = 45;

logoBottom.Border = Image.RIGHT_BORDER;

logoBottom.BorderWidth = 1;

logoBottom.BorderColor = Color.GREEN;

doc.Add(logoBottom);

// Add some more text

doc.Add(newParagraph(text));

doc.Close();

}

}

Nothing in the above example should be unfamiliar to you. We’ve covered everything there is, and each section of the code includes a comment.

That concludes basic image addition and transformation with the iTextSharp library. Now, you should be able to add images to a PDF document with spacing, borders, and so forth. Images can be placed automatically or manually. The images can also be transformed according to your needs.