1

2018 年 4 月 4 日更新:我想通了。见下文...

我正在尝试以编程方式将数百个文本框添加到 Google 幻灯片演示文稿中。我想设置文本中心水平对齐和中间垂直对齐。任何人都可以用文本框的文本举一个这样做的例子。我几乎在请求文本的每个位置都尝试了建议的 API 请求:

'ContentAlignment': 'MIDDLE'

&

'alignment': 'CENTER'

我会将这些行放在下面的代码中的什么位置?

def add_text_box(ss, org, elemID, presID):
    # Create a new square textbox, using the supplied element ID.

    height = {
        'magnitude': 50,
        'unit': 'PT'
    }
    width = {
        'magnitude': 200,
        'unit': 'PT'
    }
    requests = []

    requests.append(
        {
            'createShape': {
                'objectId': elemID,
                'shapeType': 'TEXT_BOX',
                'elementProperties': {
                    'pageObjectId': org,
                    'size': {
                        'height': height,
                        'width': width
                    },
                    'transform': {
                        'scaleX': 1,
                        'scaleY': 1,
                        'translateX': 10,
                        'translateY': 10,
                        'unit': 'PT'
                    }
                }
            }
        }
    )

    # Insert text into the box, using the supplied element ID.
    requests.append(
        {
            'insertText': {
                'objectId': elemID,
                'insertionIndex': 0,
                'text': 'Position\nName\nDate'
            }
        }
    )

    # Change text style based on position in text string
    requests.append(
        {
            'updateTextStyle': {
                'objectId': elemID,
                'textRange': {
                    'type': 'FIXED_RANGE',
                    'startIndex': 0,
                    'endIndex': 8
                },
                'style': {
                    'fontFamily': 'Arial',
                    'fontSize': {
                        'magnitude': 10,
                        'unit': 'PT'
                    },
                },
                'fields': 'fontFamily,fontSize'
            }
        }
    )
    requests.append(
        {
            'updateTextStyle': {
                'objectId': elemID,
                'textRange': {
                    'type': 'FIXED_RANGE',
                    'startIndex': 9,
                    'endIndex': 13
                },
                'style': {
                    'fontFamily': 'Arial',
                    'bold': True,
                    'fontSize': {
                        'magnitude': 14,
                        'unit': 'PT'
                    },
                },
                'fields': 'fontFamily,bold,fontSize'
            }
        }
    )
    requests.append(
        {
            'updateTextStyle': {
                'objectId': elemID,
                'textRange': {
                    'type': 'FIXED_RANGE',
                    'startIndex': 14,
                    'endIndex': 18
                },
                'style': {
                    'fontFamily': 'Arial',
                    'fontSize': {
                        'magnitude': 8,
                        'unit': 'PT'
                    },
                },
                'fields': 'fontFamily,fontSize'
            }
        }
    )

    # Execute the request.
    body = {
        'requests': requests
    }
    response = ss.presentations().batchUpdate(presentationId=presID, body=body).execute()
    create_shape_response = response.get('replies')[0].get('createShape')
    print('Created textbox with ID: {0}'.format(create_shape_response.get('objectId')))

OR 另一个requests字符串中的代码。

更新:

要使形状中的文本水平居中,请在原始代码中添加以下内容:

requests.append(
    {
        'updateParagraphStyle': {
            "objectId": elemID,
            "style": {
                "alignment": "CENTER"
            },
            "fields": 'alignment',
        }
    }
)

要使形状中的文本垂直定位在 MIDDLE 中,以及绘制实心轮廓并填充形状,请在原始代码中添加以下内容:

requests.append(
        {
            "updateShapeProperties": {
                "objectId": elemID,
                "fields": "outline,shapeBackgroundFill,contentAlignment",
                "shapeProperties": {
                    "shapeBackgroundFill": {
                        "solidFill": {
                            "alpha": 0.6,
                            "color": {
                                "themeColor": "ACCENT5"
                            }
                        }
                    },
                    "outline": {
                        "dashStyle": "SOLID",
                        "outlineFill": {
                            "solidFill": {
                                "alpha": 1,
                                "color": {
                                    "themeColor": "ACCENT5"
                                }
                            }
                        },
                        "weight": {
                            "magnitude": 3,
                            "unit": "PT"
                        }
                    },
                    "contentAlignment": 'MIDDLE'
                }
            }
        }
    )
4

1 回答 1

0

其中一条评论要求提供可行的解决方案。这是在 Google batchUpdate 中。读取学生名册并为每个学生创建一张幻灯片,该学生的姓名在左上角的文本框中。我预计更换大师或背景来创建不同的任务。

function createSlideDeck(studentObj, assignNm, presId) {   console.log('= = = = = = = = = = Begin createSlideDeck for ', assignNm, ' = = = = = = = = = = ');   const ui = SpreadsheetApp.getUi();

  const ss = SpreadsheetApp.getActiveSpreadsheet();   const ssId = ss.getId();

  // - - - - - - - - - - - - - create page for each student - - - - -
- - - - - - - -    console.log('# students: ', studentObj.length);   let updtReqArr = []
    , pageId, pageElementId
    , inObj = {}
    , slideObj = {};

  for (let i = 0; i < studentObj.length; i++) {
    console.log('+ + + + + + + + + i: ', i, ' + + + + + + + + +');
    console.log('student: ', studentObj[i].first);
    //  add a slide
    pageId = Utilities.getUuid();
    console.log('pageId: ', pageId);

    slideObj = [{
      'createSlide': {
        'objectId': pageId,
        'insertionIndex': 1,
        'slideLayoutReference': {
          'predefinedLayout': 'BLANK'   // name of master
        }
      }
    }];
    console.log('slideObj: ', JSON.stringify(slideObj));
    updtReqArr.push(slideObj);
    console.log('updtReqArr.length: ', updtReqArr.length);

    let sORi = 'solid';
    inObj = { 'red': 0.988, 'green': 0.97, 'blue': 0.87, 'alpha': 0.3 };
    bkgrdStyle = createBkgrdStyle(pageId, sORi, inObj);
    updtReqArr.push(bkgrdStyle);
    console.log('bkgrdStyle: ', JSON.stringify(bkgrdStyle));
    console.log('updtReqArr.length: ', updtReqArr.length);

    //  add a shape
    pageElementId = Utilities.getUuid();
    //      console.log('pageElementId: ', pageElementId );
    let shapeEnum = 'TEXT_BOX';
    inObj = {
      'size': { 'height': 35, 'width': 100, 'top': 10, 'left': 10 }
      ,'text': studentObj[i].first
      ,'shapeFill': { 'red': 0.988, 'green': 0.97, 'blue': 0.87, 'alpha': 0 }
      ,'border': { 'red': 0.988, 'green': 0.97, 'blue': 0.87, 'alpha': 0, 'weight': 0 }
      ,'txtProperties': { 'fntFam': "Corsiva", 'fntSz': 16,
         'red': 0.988, 'green': 0.97, 'blue': 0.87,
         'redT': 0.058, 'greenT': 0.045, 'blueT': 0.176 }  
    };
    shapePkg = createShapeObj(pageId, pageElementId, shapeEnum, inObj)
    updtReqArr.push(shapePkg.createShape);
    console.log('createShape: ', JSON.stringify(shapePkg.createShape));
    console.log('updtReqArr.length: ', updtReqArr.length);
    updtReqArr.push(shapePkg.updtShpProps);
    console.log('updtShpProps: ', JSON.stringify(shapePkg.updtShpProps));
    console.log('updtReqArr.length: ', updtReqArr.length);
    updtReqArr.push(shapePkg.updtTxtStyle);
    console.log('updtTxtStyle: ', JSON.stringify(shapePkg.updtTxtStyle));
    console.log('updtReqArr.length: ', updtReqArr.length);

    //    pres.addEditor(studentObj[i].schoolEmail);  // created with batchUpdate after all students
    console.log('slide set up for add: ', studentObj[i].first);
    console.log('end of a student - updtReqArr.length: ', updtReqArr.length);
    response = Slides.Presentations.batchUpdate({ 'requests': updtReqArr }, presId);
    console.log('response: ', response );
    updtReqArr = [];   }  //  end loop for each student 

  console.log('after student loop updtReqArr.length: ', updtReqArr.length); //  response = Slides.Presentations.batchUpdate({ 'requests': updtReqArr }, presId); //  console.log('response: ', response );   DriveApp.getFileById(presId)
    .setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.EDIT);

  console.log('End createSlideDeck'); }

这一切同时运行

/**

  NOTES: 'red':'num','green':'num', 'blue':'num', 'alpha':'num'}  
              where num is a value between 1.0 and 0.0
              get this number by dividing the 0 - 255 number by 255
              alpha is the value for alpha. a value of 1.0 corresponds to a 
              solid color, whereas a value of 0.0 corresponds to a completely 
              alphaparent color.  Use alpha to get lighter colors.
   paramaters
      pageId:  id of individual slide
      shapeEnum:    'solid' color or 'image'
      inObj= {
              'size': {
                'height':num
               ,'width':num
               ,'top':num
               ,'left':num
              },
             ,'text':string
             ,shapeFill: {
               ,'red'
               ,'green'
               ,'blue'
               ,'alpha'
             },
             ,border: {
               ,'red'
               ,'green'
               ,'blue'
               ,'alpha'
               ,'weight'
             }
             . . . . stuff used to set properties
            }
     returns shapeObj
     
 */
function createShapeObj(pageId, pageElementId, shapeEnum, inObj) {
  console.log('Begin createShapeObj - inObj.text: ', inObj.text);
  let shapeObj = [{
    'createShape': {
      'objectId': pageElementId,
      'shapeType': 'TEXT_BOX',
      'elementProperties': {
        'pageObjectId': pageId,
        'size': {
          'width': {
            'magnitude': inObj.size.width,
            'unit': 'PT'
          },
          'height': {
            'magnitude': inObj.size.height,
            'unit': 'PT'
          }
        },  // end size
        'transform': {
          'scaleX': 1,
          'scaleY': 1,
          'translateX': inObj.size.left,
          'translateY': inObj.size.top,
          'unit': 'PT'
        }
      }  //  end elementProperties
    }   // end createShape
  }, {
    'insertText': {
      'objectId': pageElementId
     ,'text': inObj.text
     ,'insertionIndex': 0
  }
  }];

  //  set shape properties
  shapeUpdObj = [{}];
  shapeUpdObj = updtShpProps(pageElementId, inObj);

  //  style the text
  txtStyleObj = [{}];
  txtStyleObj = updtTxtStyle(pageElementId, inObj);

  shapePkg = { 'createShape': shapeObj, 'updtShpProps': shapeUpdObj, 'updtTxtStyle': txtStyleObj };
  return shapePkg;
}

下一块代码

function updtShpProps(pageElementId, inObj) {
  shapeUpdObj = [{
    'updateShapeProperties': {
      'objectId': pageElementId
     ,"fields": "shapeBackgroundFill.solidFill.color"
     ,"shapeProperties": {
        "contentAlignment": 'MIDDLE'
       ,"shapeBackgroundFill": {
          "propertyState": 'RENDERED'
         ,"solidFill": {
            "color": {
                'rgbColor': {
                  "red": inObj.shapeFill.red,
                  "green": inObj.shapeFill.green,
                  "blue": inObj.shapeFill.blue
                }
            },
            "alpha": inObj.shapeFill.trans
          }
        },
        "outline": {  // border
          "outlineFill": {
            "solidFill": {
              "color": {
                'rgbColor': {
                  "red": inObj.border.red,
                  "green": inObj.border.green,
                  "blue": inObj.border.blue
                }
              },
              "alpha": inObj.border.trans
            }
          },
          "weight": {
            "magnitude": inObj.border.weight,
            "unit": 'PT'
          }
        }  // end outline / border properties
      }  // end shapeProperties
    }
  }, {                // end updateShapeProperties
      'updateParagraphStyle': {
        'objectId': pageElementId
       ,'textRange': {
         'type': "ALL"
        }
       ,'style': {
          "alignment": "CENTER"
        }
       ,'fields':'*'
      }
    }  // end update paragraph style
    ];  // end shapeUpdObj

  return shapeUpdObj;
}

这是最后一点

function updtTxtStyle(pageElementId, inObj) {
  txtStyleObj = [{
    'updateTextStyle': {
      'objectId': pageElementId
     ,'fields': 'foregroundColor,bold,italic,fontFamily,fontSize,underline'
     ,'style': {
//        This did not seem necessary but it ran successfully
//        "backgroundColor": {
//          'opaqueColor': {
//            "rgbColor":  {
//              "red": inObj.red,
//              "green": inObj.green,
//              "blue": inObj.blue
//            }
//          }
//        }
//       ,'foregroundColor': {
//          'opaqueColor': {
//            "rgbColor":  {
//              "red": inObj.redT,
//              "green": inObj.greenT,
//              "blue": inObj.blueT
//            }
//          }
//        }
//            'themeColor': 'ACCENT5'   // https://developers.google.com/slides/reference/rest/v1/presentations.pages/other
         'bold': true
        ,'italic': false
        ,'underline': false
        ,'fontFamily': inObj.txtProperties.fntFam
        ,'fontSize': {
           'magnitude': inObj.txtProperties.fntSz
          ,'unit': 'PT'
        }
      } 
     ,'textRange': {
        'type': 'ALL'
      }
    }  // end update text style
  }]

  return txtStyleObj;
}

这花了很长时间,但我成功地通过一次深入了解文档步骤,对每个添加进行测试。祝大家好运。

于 2021-03-17T18:27:51.107 回答