HTML JPG PDF XML DOCX
  Product Family
PDF

Get link by Id from PDF via PDf.Cloud Python SDK

API for getting link by Id from PDF documents using server-side Python API.

Get Started

How to extract link annotation by Id from PDF documents using Cloud Python SDK

To get links from PDF, we’ll use Aspose.PDF Cloud Python SDK. This Cloud SDK assists Python programmers in developing cloud-based PDF creator, annotator, editor, and converter apps using Python programming language via Aspose.PDF REST API. Simply create an account at Aspose for Cloud and get your application information. Once you have the App SID & key, you are ready to give the Aspose.PDF Cloud Python SDK. If the python package is hosted on Github, you can install directly from Github:

Installation from Github



    pip install git+https://github.com/aspose-pdf-cloud/aspose-pdf-cloud-python.git

Package Manager Console Command


    pip install asposepdfcloud

Steps to get link by Id using Python SDK

Aspose.PDF Cloud developers can easily extract link annotation by Id from PDF documents. Developers need just a few lines of code.

  1. Install Python SDK
  2. Create a new Configuration object with your Application Secret and Key
  3. Create an object to connect to the Cloud API
  4. Upload your document file
  5. Extract link annotation by Id from PDF documents using GetLinkAnnotation function
  6. Checks the response and logs the result
  7. If the operation is successful, you can print the link annotation or use the link annotation in another way
 

This sample code shows getting link annotation by Id from PDF document

    
    import json
    import logging
    from pathlib import Path
    from asposepdfcloud import ApiClient, PdfApi

    # Configure logging
    logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")


    class Config:
        """Configuration parameters."""
        CREDENTIALS_FILE = Path(r"..\\credentials.json")
        LOCAL_FOLDER = Path(r"C:\Samples")
        PDF_DOCUMENT_NAME = "sample.pdf"
        LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
        PAGE_NUMBER = 2
        LINK_FIND_ID = "GI5UO32UN5KVESKBMN2GS33OHMZTEMJMGUYDQLBTGYYCYNJSGE"


    class PdfLinks:
        """Class for managing PDF links using Aspose PDF Cloud API."""

        def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
            self.pdf_api = None
            self._init_api(credentials_file)

        def _init_api(self, credentials_file: Path):
            """Initialize the API client."""
            try:
                with credentials_file.open("r", encoding="utf-8") as file:
                    credentials = json.load(file)
                    api_key, app_id = credentials.get("key"), credentials.get("id")
                    if not api_key or not app_id:
                        raise ValueError("Error: Missing API keys in the credentials file.")
                    self.pdf_api = PdfApi(ApiClient(api_key, app_id))
            except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
                logging.error(f"Failed to load credentials: {e}")

        def upload_document(self):
            """Upload a PDF document to the Aspose Cloud server."""
            if self.pdf_api:
                file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
                try:
                    self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
                    logging.info(f"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
                except Exception as e:
                    logging.error(f"Failed to upload file: {e}")

        def show_links_array(self, links, prefix):
            for item in links:
                logging.info(f"{prefix} Link ID: '{item.id}' - Link Action: '{item.action}'")

        def get_link_by_id(self, link_id: str):
            """Get hyperlink annotation using the specific Id in PDF document."""
            if self.pdf_api:
                try:
                    result_link = self.pdf_api.get_link_annotation(Config.PDF_DOCUMENT_NAME, link_id)
                    if result_link.code == 200:
                        self.show_links_array([result_link.link], "Find: ")
                except Exception as e:
                    logging.error(f"Error while adding link: {e}")

    if __name__ == "__main__":
        pdf_links = PdfLinks()
        pdf_links.upload_document()
        pdf_links.get_link_by_id(Config.LINK_FIND_ID)
 

Work with the Links in PDF via Python SDK

By extracting links, one can systematically verify the validity and relevance of each URL, ensuring that all references are current and functional.​ For tasks such as downloading linked documents or conducting batch analyses, extracting URLs enables automation, saving time and reducing manual effort. Extract the Links from PDF documents with Aspose.PDF Cloud Python SDK.

With our Python SDK you can

  • Add PDF document’s header & footer in text or image format.
  • Add tables & text or image stamps to PDF documents.
  • Append multiple PDF documents to an existing file.
  • Work with PDF attachments, annotations, & form fields.
  • Apply encryption or decryption to PDF documents & set a password.
  • Delete all stamps & tables from a page or entire PDF document.
  • Delete a specific stamp or table from the PDF document by its ID.
  • Replace single or multiple instances of text on a PDF page or from the entire document.
  • Extensive support for converting PDF documents to various other file formats.
  • Extract various elements of PDF files & make PDF documents optimized.
  • You can try out our free App to test the functionality.

  •