Search code examples
javascriptnode.jsjsongoogle-slides-api

Google Slides API cannot read content of slide from an instance of page (Node.Js)


I am trying to read text from a slide presentation (as a work around to copying and pasting since all of the slides have the same exact format). When using this code:

res.data.pageElements.forEach((file) => {
    let textElements = file.shape.text.textElements;
    textElements.forEach(function(each){
        console.log(each.textRun.content);
    });
});

Even though the response says its there if I use console.log(res.data.pageElements.shape.text.textElements.textRun), referencing the way I did, returns undefined.

Please let me know if there is a solution to my problem, or if you know a work around to copy a side from presentation X to presentation Y. Thanks in advance!

There is an issue tracker for this: https://issuetracker.google.com/36761705


Solution

  • How about this modification? From your script, I supposes that you retrieve res using slides.presentations.pages.get().

    Modification point:

    • Objects with and without res.data.pageElements.shape.text.textElements.textRun are existing in the elements of the returned object.
      • res.data.pageElements which has no property of shape.
      • res.data.pageElements.shape which has no property of text.
      • res.data.pageElements.shape.text which has no property of textElements.
      • res.data.pageElements.shape.text.textElements which has no property of textRun.

    I think that this might be the reason of your issue.

    Modified script:

    slides.presentations.pages.get({
      presentationId: presentationId,
      pageObjectId: pageObjectId,
    }, (err, res) => {
      if (err) {
        console.log(err);
      } else {
        res.data.pageElements.forEach((file) => {
          if (file.shape && file.shape.text && file.shape.text.textElements) {
              let textElements = file.shape.text.textElements;
              textElements.forEach(function(each) {
              if ("textRun" in each) {
                console.log(each.textRun.content);
              }
            });
          }
        });
      }
    });
    

    Note:

    • I think that you can also use if ("shape" in file && "text" in file.shape && "textElements" in file.shape.text) { instead of if (file.shape && file.shape.text && file.shape.text.textElements) {.
    • If you retrieve res using slides.presentations.get(), please modify res.data.pageElements.forEach((file) => {}) to res.data.slides.forEach((slide) => {slide.pageElements.forEach((file) => {})}).

    If I misunderstand about your issue, please tell me. I would like to modify it.