Allen
Allen

Reputation: 48

itextsharp image with hyperlink

I have created a pdf with an image in it using itextsharp library and c#. Now i need to have a hyperlink on that image so that when clicked on it, it goes to a specific site. How do i do it? I was trying to find a property linked to the image object but couldn't.

Upvotes: 3

Views: 4191

Answers (3)

prueba prueba
prueba prueba

Reputation: 702

I know this is an old question, but the answer selected was not enough for me because I don't have control on the position of the hyperlink area. Even if I change the value of the Chunk's offset the image moves but the link stays in the same position.

The next code works for itextsharp v5.1.13.1.

MemoryStream stream = new MemoryStream();
Document doc = new Document();
doc.SetPageSize(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(doc, stream);
doc.Open();
PdfContentByte canvas = writer.DirectContentUnder;

doc.NewPage();

float llx = 100, lly = 100;
string imgPath = "image.png", url = "http://google.com/";
Image img = Image.GetInstance(imgPath);
img.SetAbsolutePosition(llx, lly);
canvas.AddImage(img);

PdfAnnotation annotation = PdfAnnotation.CreateLink(writer,
   new Rectangle(img.AbsoluteX, img.AbsoluteY, img.AbsoluteX + img.Width, img.AbsoluteY + img.Height),,
PdfAnnotation.HIGHLIGHT_INVERT, new PdfAction(url));
canvas.AddAnnotation(annotation, false);

What this code does is to put an image in the page an then create an hyperlink area which will take the same position and size of the image, you just have to define the llx, lly, imgPath and url. That's it.

Upvotes: 0

petrosmm
petrosmm

Reputation: 550

for iText7

var url = "micorosft.com";
var fbImageData = ImageDataFactory.Create("c:/temp/fb.png");
var fbImage = new Image(fbImageData);
var twImageData = ImageDataFactory.Create("c:/temp/tw.png");
var twImage = new Image(twImageData);

fbImage.SetMaxWidth(16);
fbImage.SetMaxHeight(16);
fbImage.SetAction(PdfAction.CreateURI($"https://www.facebook.com/sharer/sharer.php?u={url}&quote={"quotegoeshere"}"));

twImage.SetMaxWidth(16);
twImage.SetMaxHeight(16);
twImage.SetAction(PdfAction.CreateURI($"https://twitter.com/intent/tweet?text={"randomtextgoeshere"}" + $" {url}"));

Upvotes: 1

Erre Efe
Erre Efe

Reputation: 15577

You must use an Anchor

Chunk cImage = new Chunk(yourImage, 0, 0, false); 
Anchor anchor = new Anchor(cImage); 
anchor.Reference = "www.yourAddress.com"; 
document.Add(anchor); 

Upvotes: 5

Related Questions