google-api-clientgoogle-slides-api

Google Slides API, positioning of image on the slide


I am inserting an Image to a Google Slide using Google Slides API , My code is

    $emu4M = array('magnitude' => 5500000, 'unit' => 'EMU');
    $requests = array();
    $requests[] = new Google_Service_Slides_Request(array(
      'createImage' => array (
        'objectId' => '303030',
        'url' => $imageUrl,
        'elementProperties' => array(
          'pageObjectId' => $pageId,
          'size' => array(
            'height' => $emu4M,
            'width' => $emu4M
          ),
          'transform' => array(
            'scaleX' => 1,
            'scaleY' => 1,
            'translateX' => 5000,
            'translateY' => 5000,
            'unit' => 'EMU'
          )
        )
      )
    ));

It works fine but the image inserted is like this

Slide Created by Google Slides API

I want the image to appear in center and reduce padding from top. Any help?


Solution

  • Google Slides API may change your transform request result to something you have not asked:

    When you create a page element, you can specify a size and transform that provide a certain visual result. However, the API may replace your provided values with other ones that yield the same visual appearance. In general, if you write a size using the API, you are not guaranteed to be returned the same size.

    Source: https://developers.google.com/slides/api/guides/transform#the_might_refactor_your_values


    Relatively safe way of inserting image to center of Google Slide is inserting via ReplaceAllShapesWithImageRequest.

    First you need to create placeholder shape and place it in the center of the slide:

    enter image description here

    Then replace the shape with your image (example in Google Apps Script language):

    function insertImageCentered()
    {
      var presentation = SlidesApp.getActivePresentation();
      
      var requests = [{
        "replaceAllShapesWithImage": {
          "imageUrl": "https://docs.google.com/drawings/d/e/2PACX-1vR5mi6ujksb_2WtTFmk39IPYBIBlJ6WkzM1nsys9cT4Wquik627DDIRXzoYTgHPKX3fcvJzG9inDmJt/pub?w=960&h=720",
            "imageReplaceMethod": "CENTER_INSIDE",
            "pageObjectIds": [presentation.getSlides()[0].getObjectId()],
            "containsText": {
              "text": "{{CENTERED_SHAPE}}",
              "matchCase": false
            }
         }
       }];
      
       Slides.Presentations.batchUpdate({'requests': requests}, presentation.getId());
    }
    

    Resulted image in center of the slide:

    enter image description here