Penguen
Penguen

Reputation: 17298

How to Add image in pdf using C# and iTextSharp?

I need your help adding an image to a PDF.

I'm using:

string imgPath2 = localPath + "\\TempChartImages\\" + LegendPath;
img2.Save(imgPath2);
ith.WriteImage(imgPath2, 80);

But this code gives me the error:

Use of unassigned local variable img2

How can I solve this error?

Upvotes: 2

Views: 8037

Answers (6)

DaNet
DaNet

Reputation: 438

You have to create a getinstance of the image.

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("path of the image");

Upvotes: 1

Nathan
Nathan

Reputation: 1520

I believe you have to instantiate first the Image.

Image img2 = new Image();

it solved my problems. Hope it will solve yours.

Upvotes: 1

STW
STW

Reputation: 46434

it's a hunch, but if you're assigning the value of img2 inside a Try-Catch block you might be hitting an exception that prevents the assignment from taking place. For example:

var img2;
try
{
    var x = 5 / 0; // Generate a DivideByZero exception
    img2 = GetImage(); // <-- the above exception will prevent this code from executing
}
catch
{
}
img2.Save(imgPath2); <-- img2 wasn't assigned, so another exception will occur

Upvotes: 2

Kelsey
Kelsey

Reputation: 47776

When you declare a variable, in your case img2, without assigning a value it is pointing to absolutely nothing. Make sure you initialize img2 to something before using it.

I think what you want your img2.Save line to be changed to:

Image img2 = Image.FromFile(yourInitialImageHere);  // You could be reading from memory as well.
img2.Save(imgPath2);

I could be way off though as your snippet of code is pretty vague.

Upvotes: 2

Jeffrey
Jeffrey

Reputation: 1667

Here is the iTextSharp tutorial on images. Without seeing more of your code, it's tough to judge what piece of code from this you'll need.

Upvotes: 2

Jeffrey
Jeffrey

Reputation: 1667

You'll need some third-party tool for this.

Upvotes: 1

Related Questions