python程序创建了一个谷歌幻灯片演示,但结果是空的

问题描述

我有几个 jpg 图像文件,我需要以编程方式将它们插入到 Google 幻灯片演示文稿中。第一步是创建一个程序,该程序只生成一张幻灯片并将一张图像插入幻灯片。如果这成功了,我将在我的图像上循环放大代码代码如下:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import library_JP

# If modifying these scopes,delete the file token.pickle.
#ScopES = ['https://www.googleapis.com/auth/presentations.readonly']
ScopES = ['https://www.googleapis.com/auth/presentations']

# The ID of a sample presentation.
PRESENTATION_ID = '1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc'
PRESENTATION_ID = '1tWESMVHXsbbW-rro6wdeDQL3ygkxAf3c0xSd-JK-oXg'
presentation_id = '1tWESMVHXsbbW-rro6wdeDQL3ygkxAf3c0xSd-JK-oXg'

def main():
    """Shows basic usage of the Slides API.
    Prints the number of slides and elments in a sample presentation.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens,and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle','rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available,let the user log in.
    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)
        # Save the credentials for the next run
        with open('token.pickle','wb') as token:
            pickle.dump(creds,token)

    service = build('slides','v1',credentials=creds)

    # Call the Slides API
    IMAGE_URL = ('https://www.google.com/images/branding/'
             'googlelogo/2x/googlelogo_color_272x92dp.png')
#    page_id = '3b330c04-6eb2-11eb-9439-0242ac130002'
    page_id = '0c00dd21-da6d-4b9a-9694-3b9e81b2ab1b'
    requests = [
    {
        'createSlide': {
#            'objectId': page_id,'insertionIndex': '1','slideLayoutReference': {
                'predefinedLayout': 'TITLE_AND_TWO_COLUMNS'
            }
        }
    }
              ]


    title = 'JP_february13-2021 '
    print('debug requests before creating pres ',requests)
    body0 = {'title': title}
#
    presentation = service.presentations().create(body=body0).execute()
    print('Created presentation with ID: {0}'.format(
    presentation.get('presentationId')))
    body = { 'requests': requests}
#
    response = service.presentations() \
    .batchUpdate(presentationId=presentation_id,body=body).execute()
    create_slide_response = response.get('replies')[0].get('createSlide')
    print('Created slide with ID: {0}'.format(
    create_slide_response.get('objectId')))
#
    requests = []
    image_id = 'MyImage_01'
    emu4M = {
    'magnitude': 4000000,'unit': 'EMU',}
    requests.append({
     'createImage': {
        'objectId': image_id,'url': IMAGE_URL,'elementProperties': {
            'pageObjectId': page_id,'size': {
                'height': emu4M,'width': emu4M
            },'transform': {
                'scaleX': 1,'scaleY': 1,'translateX': 100000,'translateY': 100000,'unit': 'EMU'
                         }
            }
                    }
                    })


    response = service.presentations() \
    .batchUpdate(presentationId=presentation_id,body=body).execute()
    create_image_response = response.get('replies')[0].get('createImage')
#    print('Created image with ID: {0}'.format(
#    create_image_response.get('objectId')))

if __name__ == '__main__':
    main()


程序的输出是:

python quickstart_JP5.py
debug requests before creating pres  [{'createSlide': {'insertionIndex': '1','slideLayoutReference': {'predefinedLayout': 'TITLE_AND_TWO_COLUMNS'}}}]
Created presentation with ID: 1gRl0h60XXK8_p7kfn4pgBe212ncKHbScj1Y7pesjZlo
Created slide with ID: SLIDES_API1707490034_0

但是,当我使用带有上面的演示文稿 ID 的 chrome 时,结果不是我所期望的:

https://docs.google.com/presentation/d/1gRl0h60XXK8_p7kfn4pgBe212ncKHbScj1Y7pesjZlo/edit#slide=id.p

解决方法

以下代码按预期工作并修复了之前报告的问题:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
#
# If modifying these scopes,delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/presentations']


def main():
    """Shows basic usage of the Slides API.
    Prints the number of slides and elments in a sample presentation.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens,and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle','rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available,let the user log in.
    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)
        # Save the credentials for the next run
        with open('token.pickle','wb') as token:
            pickle.dump(creds,token)

    service = build('slides','v1',credentials=creds)

    # Call the Slides API
    IMAGE_URL = ('https://www.google.com/images/branding/'
             'googlelogo/2x/googlelogo_color_272x92dp.png')


    title = 'JP_february13-2021 '
    body0 = {'title': title}
#
    presentation = service.presentations().create(body=body0).execute()
    print('Created presentation with ID: {0}'.format(
    presentation.get('presentationId')))
    XXX = presentation.get('presentationId')
#
    requests = [
    {
        'createSlide': {
            'insertionIndex': '1','slideLayoutReference': {
                'predefinedLayout': 'TITLE_AND_TWO_COLUMNS'
            }
        }
    }
              ]

    body1 = { 'requests': requests}
#
    response = service.presentations() \
    .batchUpdate(presentationId=XXX,body=body1).execute()
    create_slide_response = response.get('replies')[0].get('createSlide')
    print('Created slide with ID: {0}'.format(
    create_slide_response.get('objectId')))
    YYY = create_slide_response.get('objectId')
#
    requests = []
    image_id = 'MyImage_01'
    emu4M = {
    'magnitude': 4000000,'unit': 'EMU',}
    requests.append({
     'createImage': {
        'objectId': image_id,'url': IMAGE_URL,'elementProperties': {
            'pageObjectId': YYY,'size': {
                'height': emu4M,'width': emu4M
            },'transform': {
                'scaleX': 1,'scaleY': 1,'translateX': 100000,'translateY': 100000,'unit': 'EMU'
                         }
            }
                    }
                    })

    body2 = {'requests': requests}
    response = service.presentations() \
    .batchUpdate(presentationId=XXX,body=body2).execute()
    create_image_response = response.get('replies')[0].get('createImage')
#    print('Created image with ID: {0}'.format(
#    create_image_response.get('objectId')))

if __name__ == '__main__':
    main()

原始代码中的问题是在如下指令中传递了错误的变量:

    response = service.presentations() \
    .batchUpdate(presentationId=XXX,body=body1).execute()

作为更正的结果,程序返回一个地址,如

presentation with ID: 1JHjscoAl3perOnqeJQocpt0YmwHSuXLu5fCgATCY2dc

可以在 url 中“手动”使用以访问谷歌幻灯片演示

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...