Search code examples
pythongoogle-slides-api

Python Google Slides API How to insert a text with hyperlink?


I have looked through the documentation of Google Slides API, but I can't seem to find the section where you can insert a text with hyperlink. I am using python for integrating the API.


Solution

  • There are 2 methods to add links to a Google Slide, you can use TextStyle which is under the Text for presentations.pages or you can use UpdateTextStyleRequest under the Method: presentations.batchUpdate.

    Here is a sample using UpdateTextStyleRequest, I first create a shape textbox, inserted the text New URL link added!, and update the style to hyperlink for the words URL link:

    from __future__ import print_function
    
    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    
    SCOPES = ['https://www.googleapis.com/auth/presentations']
    
    # The ID of the presentation 
    PRESENTATION_ID = 'SlideID'
    
    
    def main():
       
        creds = None
        
        if os.path.exists('token.json'):
            creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server(port=0)
            with open('token.json', 'w') as token:
                token.write(creds.to_json())
    
        try:
            service = build('slides', 'v1', credentials=creds
            element_id = 'MyTextBox_10'
            page_id = 'g1e436298788_0_0'
            pt = {
                'magnitude': 200,
                'unit': 'PT'
            }
            requests = [
                {
                    'createShape': {
                        'objectId': element_id,
                        'shapeType': 'TEXT_BOX',
                        'elementProperties': {
                            'pageObjectId': page_id,
                            'size': {
                                'height': pt,
                                'width': pt
                            },
                            'transform': {
                                'scaleX': 1,
                                'scaleY': 1,
                                'translateX': 50,
                                'translateY': 100,
                                'unit': 'PT'
                            }
                        }
                    }
                },
    
                # Insert text into the box, using the supplied element ID.
                {
                    'insertText': {
                        'objectId': element_id,
                        'insertionIndex': 0,
                        'text': 'New URL link added!'
                    }
                },
    
                # Insert the URL for in the speficy range.
                {
                    'updateTextStyle': {
                        'objectId': element_id,
                        'textRange': {
                            'type': 'FIXED_RANGE',
                            'startIndex': 4,
                            'endIndex': 12
                        },
                        'style': {
                            'link': {
                                'url': 'www.google.com'
                            }
                        },
                        'fields': 'link'
                    }
                }
                
    
            ]
    
            # Execute the request.
            body = {
                'requests': requests
            }
            response = service.presentations() \
                .batchUpdate(presentationId=PRESENTATION_ID, body=body).execute()
            create_shape_response = response.get('replies')[0].get('createShape')
            print(f"Created textbox with ID:"
                  f"{(create_shape_response.get('objectId'))}")
    
        except HttpError as err:
            print(err)
    
    
    if __name__ == '__main__':
        main()
    

    And it'll look like this:

    hyperlink

    You can also review the following Google guide Editing and Styling Text