0
votes

I'm working on a script which takes text and places each paragraph in a numbered table cell. I'm running into a problem where each line break is counted as a paragraph by the script, which means my table either has empty cells or is numbered incorrectly.

Here's the working script (minus row numbering):

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

  // Get the paragraphs
  var paras = body.getParagraphs();

  // Add a table to fill in with copied content
  var addTable = body.appendTable();
  for (var i=0;i<paras.length;++i) {

    // If the paragraph is text, add a table row and insert the content.
    if(i % 2 == 0) {
      var tr = addTable.appendTableRow();
      var text = paras[i].getText();

      // Number the table rows as they're added in a cell to the left.
      for(var j=0;j<2;j++) {
        if(j == 0) {
          var td = tr.appendTableCell(i);
          } else {
            var td = tr.appendTableCell(text);
          }
        }
      }

    // Shrink left column.
    addTable.setColumnWidth(0, 65);

    // Delete the original text from the document.
    paras[i].removeFromParent();
  }
}

Here's a demo Google Doc so you can see how text formats without setting a new one up yourself if that helps.

2

2 Answers

1
votes

Logic

What you should do is to iterate each paragraph and check if that paragraph contains text. If yes, then add a row and put the text in it, else skip that paragraph and jump to the next one.

Implementation

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

    // Get the paragraphs
    var paras = body.getParagraphs();
    var addTable = body.appendTable();

    //paragraph index 
    var pIndex = 0;
    for(var i = 0 ; i < paras.length ; i++){
        var para = paras[i];
        var paraStr = para.editAsText().getText();
        // if there is string content in paragraph
        if(paraStr.length){
            var tr = addTable.appendTableRow();
            var td1 = tr.appendTableCell(pIndex);
            var td2 = tr.appendTableCell(paraStr);
            pIndex ++;
        }
        para.removeFromParent();
    }
    // Shrink left column.
    addTable.setColumnWidth(0, 65);
}

Here You get the string from paragraph var paraStr = para.editAsText().getText(); and check if the content exists if(paraStr.length) If yes then create a row, insert paragraph index and paragraph's text in it.

0
votes

Try this: tr.appendTableCell(i/2 +1)

// Number the table rows as they're added in a cell to the left.
  for(var j=0;j<2;j++) {
    if(j == 0) {
      var td = tr.appendTableCell(i/2 +1);
      } else {
        var td = tr.appendTableCell(text);
      }
    }
  }