Add Local Hyperlink in PDF using C# with Aspose.PDF - Position local hyperlink

I have two different methods for getting a local hyperlink to a different page in the PDF. Method 1 works but I can’t change the position of the hyperlink. It always appears in the same place. Method 2 doesn’t work, the hyperlink looks OK but doesn’t work when you click. How do you get a working local hyperlink where you can set its absolute position to anywhere on the page please?

        // Method 1 (link works but position never changes)

        var pdfDocument = new Aspose.Pdf.Document(pdfToRead);
        var firstPage = pdfDocument.Pages.First();

        var linkSegment = new TextSegment("click to go to page 8");

        var link = new LocalHyperlink { TargetPageNumber = 8 };
        linkSegment.Hyperlink = link;

        TextState textState = GetDefaultTextState();
        linkSegment.TextState = textState;

        var textFragment = new TextFragment();
        textFragment.Segments.Add(linkSegment);
        textFragment.Position.XIndent = 200; // has no affect
        textFragment.Position.YIndent = 300; // has no affect
        firstPage.Paragraphs.Add(textFragment);

        pdfDocument.Save(pdfToWrite);


        // Method 2 - Position works, hyperlink doesn't work (does nothing on click)

        var pdfDocument = new Aspose.Pdf.Document(pdfToRead);
        var firstPage = pdfDocument.Pages.First();

        var linkSegment = new TextSegment("click to go to page 8");

        var link = new LocalHyperlink { TargetPageNumber = 8 };
        linkSegment.Hyperlink = link; // doesn't work

        TextState textState = GetDefaultTextState();
        linkSegment.TextState = textState;

        var textFragment = new TextFragment();
        textFragment.Segments.Add(linkSegment);
        
        var textParagraph = new TextParagraph
        {
            Position = new Position(200, 200) // works
        };

        textParagraph.AppendLine(textFragment);
        
        TextBuilder textBuilder = new TextBuilder(firstPage);
        textBuilder.AppendParagraph(textParagraph);

        pdfDocument.Save(pdfToWrite);

@sfackrell2

In your Method I, please try to set the position as following:

textFragment.Position = new Position(200, 200);

In case you still face any issue, please let us know.

Hi, thank you for your reply. Setting position in this way makes no difference; I’ve already tried it

fragment.Position = new Position(500,1000); // doesn't work

This appears to have been resolved by upgrading from

“Aspose.PDF” Version=“19.1.0” to Version=“20.11.0”

I can now position the hyperlink

1 Like

@sfackrell2

It is nice to hear that you were able to resolve your issue by using the latest version. Please keep using our API and feel free to create a new topic in case you need further assistance.