Python基于Google Slides API插入JPG 生成空白演示文稿问题排查
问题根因排查
- ID错配:代码执行新建演示文稿操作后,控制台输出了刚生成的新文稿ID,但后续所有修改操作都沿用了脚本开头硬编码的旧文稿ID,所有创建幻灯片、插入图片的请求实际都提交到了旧文稿中,打开新建的空白文稿自然看不到任何内容。
- 页面ID无效:脚本里写死的
page_id既不属于新文稿,也没有和创建幻灯片时实际生成的页面ID对齐;同时createSlide请求里把自定义页面ID的逻辑注释掉了,API自动生成的幻灯片ID和代码里的硬编码值完全不匹配,插入图片的请求会因为找不到目标页面直接失效。 - 请求体未同步:创建完幻灯片后,代码重新写了一套插入图片的请求列表,但提交请求时还是用了之前存的、只有创建幻灯片操作的旧请求体,图片创建请求根本没有被发送到API。
修正后可运行的最小验证代码
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 # 如修改这些权限范围,请删除token.pickle文件 SCOPES = ['https://www.googleapis.com/auth/presentations'] # 自定义全局ID,避免硬编码旧值 NEW_PRESENTATION_TITLE = 'JP_february13-2021' CUSTOM_SLIDE_ID = 'jp_test_slide_01' CUSTOM_IMAGE_ID = 'jp_test_image_01' TEST_IMAGE_URL = ('https://www.google.com/images/branding/' 'googlelogo/2x/googlelogo_color_272x92dp.png') EMU_SIZE = { 'magnitude': 4000000, 'unit': 'EMU', } def main(): creds = None # token.pickle文件存储用户的访问与刷新令牌 if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # 无有效可用凭据时引导用户登录 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.pickle', 'wb') as token: pickle.dump(creds, token) service = build('slides', 'v1', credentials=creds) # 第一步:新建演示文稿,获取新建文稿的真实ID new_presentation = service.presentations().create(body={'title': NEW_PRESENTATION_TITLE}).execute() new_pres_id = new_presentation.get('presentationId') print(f'新建演示文稿ID: {new_pres_id}') # 第二步:在新建文稿里创建幻灯片,使用自定义固定ID slide_request = [ { 'createSlide': { 'objectId': CUSTOM_SLIDE_ID, 'insertionIndex': '0', 'slideLayoutReference': { 'predefinedLayout': 'TITLE_AND_TWO_COLUMNS' } } } ] service.presentations().batchUpdate(presentationId=new_pres_id, body={'requests': slide_request}).execute() print(f'已创建幻灯片,ID: {CUSTOM_SLIDE_ID}') # 第三步:在指定幻灯片上插入测试图片,使用自定义ID image_request = [ { 'createImage': { 'objectId': CUSTOM_IMAGE_ID, 'url': TEST_IMAGE_URL, 'elementProperties': { 'pageObjectId': CUSTOM_SLIDE_ID, 'size': { 'height': EMU_SIZE, 'width': EMU_SIZE }, 'transform': { 'scaleX': 1, 'scaleY': 1, 'translateX': 100000, 'translateY': 100000, 'unit': 'EMU' } } } } ] service.presentations().batchUpdate(presentationId=new_pres_id, body={'requests': image_request}).execute() print(f'已插入测试图片,ID: {CUSTOM_IMAGE_ID}') print(f'可访问文稿链接: https://docs.google.com/presentation/d/{new_pres_id}/edit') if __name__ == '__main__': main()
后续批量插入本地JPG的注意事项
createImage接口仅支持公网可直接访问的图片直链,本地JPG文件不能直接填本地路径,需要先上传到Google Drive设置为公开可访问,拿到文件的直链后再传入url参数。- 后续加循环逻辑时,每张幻灯片、每个图片都需要设置唯一的objectId,避免API因为ID重复报错。
内容的提问来源于stack exchange,提问作者LP0
相关产品推荐
相关产品推荐

