Extract Links

Contents
[ ]

PDF often contain interactive elements such as web links, document links, and custom actions. Using PdfContentEditor, you can programmatically extract all link annotations from a PDF. This allows you to inspect or process links, for example, to validate URLs or analyze navigation patterns in a document.

  1. Create a PdfContentEditor instance.
  2. Bind the input PDF document.
  3. Extract all links using ’extract_link()'.
  4. Iterate through extracted links.
  5. Check if a link is a LinkAnnotation and if its action is a GoToURIAction.
  6. Print the rectangle coordinates and the URI.
  7. Display a message if no links are found.
import aspose.pdf.facades as pdf_facades
from aspose.pycore import cast, is_assignable
import aspose.pydrawing as apd
import aspose.pdf as ap

import sys
from os import path

sys.path.append(path.join(path.dirname(__file__), ".."))

from config import set_license, initialize_data_dir


def extract_links(infile):
    # Create PdfContentEditor object
    content_editor = pdf_facades.PdfContentEditor()
    # Bind document to PdfContentEditor
    content_editor.bind_pdf(infile)
    # Extract links from the document
    links = content_editor.extract_link()

    count = 0
    for link in links:
        count += 1
        print(f"Link {count}: {link.rect}")
        if is_assignable(link, ap.annotations.LinkAnnotation):
            annotation = cast(ap.annotations.LinkAnnotation, link)
            if is_assignable(annotation.action, ap.annotations.GoToURIAction):
                action = cast(ap.annotations.GoToURIAction, annotation.action)
                print(f"  URI: {action.uri}")

    if count == 0:
        print("No links found")