Search code examples
pythongoogle-apigoogle-drive-apigoogle-api-python-clientgoogle-slides-api

export a Google slide as an image via Google Slides Api or Drive api


I am generating a google slide dynamically using a template ppt present in my drive. I need to convert this newly created ppt as an image and want to store this in another folder in the drive itself. I may have more than 1 slide in the presentation.

from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = (
    'https://www.googleapis.com/auth/drive',
    'https://www.googleapis.com/auth/presentations',
)
SERVICE_ACCOUNT_FILE = 'cred.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES) 

SLIDES = discovery.build('slides', 'v1', credentials=credentials)
DRIVE  = discovery.build('drive',  'v3', credentials=credentials)

TMPLFILE = 'title slide template' 

rsp = DRIVE.files().list(q="name='%s'" % TMPLFILE).execute().get('files')[0]
print(rsp)
DATA = {'name': 'Google Slides API template DEMO', 'parents': ['id_of_the_folder_for_storing_new_ppt']}
print('** Copying template %r as %r' % (rsp['name'], DATA['name']))
DECK_ID = DRIVE.files().copy(body=DATA, fileId=rsp['id']).execute().get('id')
print(DECK_ID)

print('** Replacing placeholder text')

reqs = [
    {'replaceAllText': {
        'containsText': {'text': '{{text}}'},
        'replaceText': final_til[0]
    }},
]

SLIDES.presentations().batchUpdate(body={'requests': reqs},
        presentationId=DECK_ID).execute()

### till this point I was creating a new ppt 
### now I need to save it as an image file

print('DONE')

Solution

  • The probably easiest way to implement your funcitonality is with presentations.pages.getThumbnail

    Use this method by specifying the

    • presentationId
    • slidesId of the slide you want to export
    • mimeType for export - e.g. PNG
    • thumbnailSize - in function of the desired quality for the image

    The request will return you the contentURL of type https://lh3.googleusercontent.com/XXXXXXXXXXXXXXXXXX=s1600" which you can use to either view the slide as an image in the browser or to create a file in your Drive from it.

    Sidenote:

    If you want to export the whole presentaiton rather than one slide, use Files: export instead. However, this method only allows you to export the presentation only to PDF, not to PNG (at least not directly).