Extract Links
Contents
[
Hide
]
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.
- Create a PdfContentEditor instance.
- Bind the input PDF document.
- Extract all links using ’extract_link()'.
- Iterate through extracted links.
- Check if a link is a LinkAnnotation and if its action is a GoToURIAction.
- Print the rectangle coordinates and the URI.
- 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")