Find if a Google Document is blank using google script

北战南征 提交于 2019-12-13 08:40:01

问题


How to find if a google document is blank using App script? I tried this

function myFunction() 
{
  var body = DocumentApp.getActiveDocument().getBody();
  var para = body.getParagraphs();
  var count = 0;
  for (i = 0; i < para.length; i++) 
  {
    if (para[i].getText() != "")
     count++;  
  }
  if(count=0)
   Logger.log("Empty");
  else
   Logger.log("NOT EMPTY")
}

I am sure that this works good only if the document has text content alone. I am eager to know if there is any way to find if the document is blank.


回答1:


A document always has at least one paragraph element, so you can't really rely on a zero-count return. You could check the length of the elements in the body and then trigger some more tests for a true check for blankness.

function blankDoc() {
  var body = DocumentApp.getActiveDocument().getBody();

  // Find the number of children in the body
  Logger.log(body.getNumChildren());

  for(var i = 0; i<body.getNumChildren();i++) {
    Logger.log(body.getChild(i).getType());

    // Test for text in the paragraph
    if(body.getChild(i).getType() == DocumentApp.ElementType.PARAGRAPH) {

      // get the text, check for a 0 length
      var para = body.getChild(i).asParagraph().getText();
      Logger.log(para.length);
      // use another if block to do something...
    }
  }
  // check for images
  var imgs = body.getImages();

  if(imgs.length > 0) {
    Logger.log("There's an image");
  }
}

It's not perfect, but it gets you closer. Go through the documentation on what elements to check for in the Body of the doc and just add from there.



来源:https://stackoverflow.com/questions/43999152/find-if-a-google-document-is-blank-using-google-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!