Para adicionar um slide, use o método
batchUpdate()
com o ID da apresentação e inclua um
CreateSlideRequest
no corpo da solicitação. O ID do novo slide é retornado no corpo da resposta.
Exemplo
O exemplo a seguir mostra como adicionar um slide a uma apresentação. Todos os campos
para
CreateSlideRequest
são opcionais. Este exemplo cria o slide como o segundo, com
layout TITLE_AND_TWO_COLUMNS e um ID de objeto explícito.
/** * Creates a slide * @param {string} presentationId * @param {string} pageId * @returns {*} */functioncreateSlide(presentationId,pageId){// See Presentation.insertSlide(...) to learn how to add a slide using SlidesApp.// http://developers.google.com/apps-script/reference/slides/presentation#appendslidelayoutconstrequests=[{createSlide:{objectId:pageId,insertionIndex:'1',slideLayoutReference:{predefinedLayout:'TITLE_AND_TWO_COLUMNS'}}}];// If you wish to populate the slide with elements, add element create requests here,// using the pageId.// Execute the request.try{constcreateSlideResponse=Slides.Presentations.batchUpdate({requests:requests},presentationId);console.log('CreatedslidewithID:%s',createSlideResponse.replies[0].createSlide.objectId);returncreateSlideResponse;}catch(err){// TODO (Developer) - Handle exceptionconsole.log('Failedwitherror:%s',err.error);}};
// Add a slide at index 1 using the predefined "TITLE_AND_TWO_COLUMNS" layout// and the ID "MyNewSlide_001".slideId:="MyNewSlide_001"requests:=[]*slides.Request{{
CreateSlide: &slides.CreateSlideRequest{
ObjectId: slideId,
InsertionIndex: 1,
SlideLayoutReference: &slides.LayoutReference{
PredefinedLayout: "TITLE_AND_TWO_COLUMNS",
},
},
}}// If you wish to populate the slide with elements, add create requests here,// using the slide ID specified above.// Execute the request.body:=&slides.BatchUpdatePresentationRequest{Requests:requests,}response,err:=slidesService.Presentations.BatchUpdate(presentationId,body).Do()iferr!=nil{log.Fatalf("Unable to create slide. %v",err)}fmt.Printf("Created slide with ID: %s",response.Replies[0].CreateSlide.ObjectId)
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.googleapis.json.GoogleJsonError;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.slides.v1.Slides;importcom.google.api.services.slides.v1.SlidesScopes;importcom.google.api.services.slides.v1.model.BatchUpdatePresentationRequest;importcom.google.api.services.slides.v1.model.BatchUpdatePresentationResponse;importcom.google.api.services.slides.v1.model.CreateSlideRequest;importcom.google.api.services.slides.v1.model.CreateSlideResponse;importcom.google.api.services.slides.v1.model.LayoutReference;importcom.google.api.services.slides.v1.model.Request;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.ArrayList;importjava.util.Collections;importjava.util.List;/* Class to demonstrate the use of Create Slides API */publicclassCreateSlide{/** * Creates a new slide. * * @param presentationId - id of the presentation. * @return slide id * @throws IOException - if credentials file not found. */publicstaticBatchUpdatePresentationResponsecreateSlide(StringpresentationId)throwsIOException{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(SlidesScopes.PRESENTATIONS));HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Create the slides API clientSlidesservice=newSlides.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Slides samples").build();// Add a slide at index 1 using the predefined "TITLE_AND_TWO_COLUMNS" layoutList<Request>requests=newArrayList<>();StringslideId="MyNewSlide_001";BatchUpdatePresentationResponseresponse=null;try{requests.add(newRequest().setCreateSlide(newCreateSlideRequest().setObjectId(slideId).setInsertionIndex(1).setSlideLayoutReference(newLayoutReference().setPredefinedLayout("TITLE_AND_TWO_COLUMNS"))));// If you wish to populate the slide with elements, add create requests here,// using the slide ID specified above.// Execute the request.BatchUpdatePresentationRequestbody=newBatchUpdatePresentationRequest().setRequests(requests);response=service.presentations().batchUpdate(presentationId,body).execute();CreateSlideResponsecreateSlideResponse=response.getReplies().get(0).getCreateSlide();// Prints the slide id.System.out.println("Created slide with ID: "+createSlideResponse.getObjectId());}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelyGoogleJsonErrorerror=e.getDetails();if(error.getCode()==400){System.out.printf(" Id '%s' should be unique among all pages and page elements.\n",presentationId);}elseif(error.getCode()==404){System.out.printf("Presentation not found with id '%s'.\n",presentationId);}else{throwe;}}returnresponse;}}
functioncreateSlide(presentationId,pageId,callback){constrequests=[{createSlide:{objectId:pageId,insertionIndex:'1',slideLayoutReference:{predefinedLayout:'TITLE_AND_TWO_COLUMNS',},},},];// If you wish to populate the slide with elements, add element create requests here,// using the pageId.// Execute the request.try{gapi.client.slides.presentations.batchUpdate({presentationId:presentationId,requests:requests,}).then((createSlideResponse)=>{constobjectId=createSlideResponse.result.replies[0].createSlide.objectId;console.log(`Created slide with ID: ${objectId}`);if(callback)callback(createSlideResponse);});}catch(err){document.getElementById('content').innerText=err.message;return;}}
/** * Creates a new slide in a presentation. * @param {string} presentationId The presentation ID. * @param {string} pageId The object ID for the new slide. */asyncfunctioncreateSlide(presentationId,pageId){const{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/presentations',});constservice=google.slides({version:'v1',auth});constrequests=[{createSlide:{objectId:pageId,insertionIndex:'1',slideLayoutReference:{predefinedLayout:'TITLE_AND_TWO_COLUMNS',},},},];// If you wish to populate the slide with elements, add element create requests here,// using the pageId.// Execute the request.try{constres=awaitservice.presentations.batchUpdate({presentationId,resource:{requests,},});console.log(`Created slide with ID: ${res.data.replies[0].createSlide.objectId}`,);returnres;}catch(err){// TODO (developer) - handle exceptionthrowerr;}}
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefcreate_slide(presentation_id,page_id):""" Creates the Presentation the user has access to. Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application.\n """creds,_=google.auth.default()# pylint: disable=maybe-no-membertry:service=build("slides","v1",credentials=creds)# Add a slide at index 1 using the predefined# 'TITLE_AND_TWO_COLUMNS' layout and the ID page_id.requests=[{"createSlide":{"objectId":page_id,"insertionIndex":"1","slideLayoutReference":{"predefinedLayout":"TITLE_AND_TWO_COLUMNS"},}}]# If you wish to populate the slide with elements,# add element create requests here, using the page_id.# Execute the request.body={"requests":requests}response=(service.presentations().batchUpdate(presentationId=presentation_id,body=body).execute())create_slide_response=response.get("replies")[0].get("createSlide")print(f"Created slide with ID:{(create_slide_response.get('objectId'))}")exceptHttpErroraserror:print(f"An error occurred: {error}")print("Slides not created")returnerrorreturnresponseif__name__=="__main__":# Put the presentation_id, Page_id of slides whose list needs# to be submitted.create_slide("12SQU9Ik-ShXecJoMtT-LlNwEPiFR7AadnxV2KiBXCnE","My4ndpage")
body=Google::Apis::SlidesV1::Presentation.newrequests=[{create_slide:{object_id_prop:page_id,insertion_index:'1',slide_layout_reference:{predefined_layout:'TITLE_AND_TWO_COLUMNS'}}}]# If you wish to populate the slide with elements, add element create requests here,# using the page_id.# Execute the request.req=Google::Apis::SlidesV1::BatchUpdatePresentationRequest.new(requests:requests)response=slides_service.batch_update_presentation(presentation_id,req)create_slide_response=response.replies[0].create_slideputs"Created slide with ID: #{create_slide_response.object_id}"
Depois de criar o slide, você pode adicionar texto e formas a ele.
Preencher marcadores de posição
Os layouts geralmente têm formas de marcador de posição que são copiadas para o slide quando ele é
criado. CreateSlideRequest permite especificar os IDs de objeto usados para esses
marcadores copiados pelo campo placeholderIdMappings. Isso permite
modificar os marcadores de posição copiados na mesma solicitação batchUpdate, o que melhora
o desempenho e economiza cota. Para mais informações, consulte o
exemplo de CreateSlideRequest.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2024-12-21 UTC."],[[["This page provides instructions on adding new slides to existing Google Slides presentations."],["You need the presentation ID to add a slide, which can be found in the presentation's URL."],["The `batchUpdate()` method and `CreateSlideRequest` are used to add slides, with the new slide's ID returned in the response."],["Slides can be further customized by adding text, shapes, and filling in placeholders after creation."],["The `placeholderIdMappings` field in `CreateSlideRequest` allows for efficient modification of copied placeholders during the slide creation process."]]],[]]