Google Apps Script; Docs; convert selected element to HTML

前端 未结 2 1364
夕颜
夕颜 2021-01-15 04:40

I am just starting with Google Apps Script and following the Add-on quickstart

https://developers.google.com/apps-script/quickstart/docs

In the quickstart yo

2条回答
  •  离开以前
    2021-01-15 05:26

    There is a script GoogleDoc2HTML by Omar AL Zabir. Its purpose is to convert the entire document into HTML. Since you only want to convert rich text within the selected element, the function relevant to your task is processText from the script, shown below.

    The method getTextAttributeIndices gives the starting offsets for each change of text attribute, like from normal to bold or back. If there is only one change, that's the attribute for the entire element (typically paragraph), and this is dealt with in the first part of if-statement.

    The second part deals with the general case, looping over the indices and inserting HTML markup corresponding to the attributes.

    The script isn't maintained, so consider it as a starting point for your own code, rather than a ready-to-use library. There are some unmerged PRs that improve the conversion process, in particular for inline links.

    function processText(item, output) {
      var text = item.getText();
      var indices = item.getTextAttributeIndices();
    
      if (indices.length <= 1) {
        // Assuming that a whole para fully italic is a quote
        if(item.isBold()) {
          output.push('' + text + '');
        }
        else if(item.isItalic()) {
          output.push('
    ' + text + '
    '); } else if (text.trim().indexOf('http://') == 0) { output.push('' + text + ''); } else { output.push(text); } } else { for (var i=0; i < indices.length; i ++) { var partAtts = item.getAttributes(indices[i]); var startPos = indices[i]; var endPos = i+1 < indices.length ? indices[i+1]: text.length; var partText = text.substring(startPos, endPos); Logger.log(partText); if (partAtts.ITALIC) { output.push(''); } if (partAtts.BOLD) { output.push(''); } if (partAtts.UNDERLINE) { output.push(''); } // If someone has written [xxx] and made this whole text some special font, like superscript // then treat it as a reference and make it superscript. // Unfortunately in Google Docs, there's no way to detect superscript if (partText.indexOf('[')==0 && partText[partText.length-1] == ']') { output.push('' + partText + ''); } else if (partText.trim().indexOf('http://') == 0) { output.push('' + partText + ''); } else { output.push(partText); } if (partAtts.ITALIC) { output.push(''); } if (partAtts.BOLD) { output.push(''); } if (partAtts.UNDERLINE) { output.push(''); } } } }

提交回复
热议问题