Search code examples
c#asposeaspose.pdf

How to query the Base Paragraph element position? in order to add Link Annotation without saving the file


I'm creating a simple PDF file with some text and an hyperlink attached to the that text:

Document pdfDocument = new Document();
Page pdfPage = pdfDocument.Pages.Add();
TextFragment textFragment = new TextFragment("My Text");

Table table = new Table();            
Row row = table.Rows.Add();
Cell cell = row.Cells.Add();
        
cell.Paragraphs.Add(textFragment);            

pdfPage.Paragraphs.Add(table);    

LinkAnnotation link = new LinkAnnotation(pdfPage, textFragment.Rectangle);  //[Before Save]textFragment.Rectangle: 0,0,35.56,10
link.Action = new GoToURIAction("Link1 before save");
pdfPage.Annotations.Add(link);           

pdfDocument.Save(dataDir + "SimplePDFWithLink.pdf");

The problem is that the link annotation is being assign to the before save rectangle [0,0,33.56,10] at the bottom of the screen where's the textFragment is being added to a different rectangle (I can't set here the Position property because I don't know it, it is relative to the cell's table).

In order to solve this I've tried saving the page and only then searching the textFragment using TextFragmentAbsorber

pdfDocument.Save(dataDir + "SimplePDFWithLink.pdf");

//[After Save]textFragment.Rectangle: 0,0,90,770

TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber();
pdfPage.Accept(textFragmentAbsorber);

foreach (TextFragment absorbedTextFragment in textFragmentAbsorber.TextFragments)
{
    link = new LinkAnnotation(pdfPage, absorbedTextFragment.Rectangle);
    link.Action = new GoToURIAction("Link 2 after save");
    pdfPage.Annotations.Add(link);
}

pdfDocument.Save(dataDir + "SimplePDFWithLink.pdf");

My Question:

Is is possible to add a simple link to a TextFragment (which is BaseParagraph not StructureElement) without saving the document first?

Here is a simple demo of the outcome, you can see that before saving the document the link is added to the left bottom of the document instead of the text rectangle:

enter image description here

Update: If I specify the TextFragment's Position value with some arbitrary values, the link is then added exactly to the text, but I don't know what will be the Position value of the element because it being built dynamically using a Table.


Solution

  • Working with TextFragment and TextSegment does work and adds the link without pre-saving the file:

    TextFragment textFragment = new TextFragment("My Text");
    TextSegment textSegment = new TextSegment("Link to File");
    textSegment.Hyperlink = new Aspose.Pdf.WebHyperlink("www.google.com");
    textFragment.Segments.Add(textSegment);
    

    It is worth to mention it is works well when linking to a file on the user's file-system like:

    textSegment.Hyperlink = new Aspose.Pdf.WebHyperlink("Files\foo.png");