print mailer
print mailer

Reputation: 41

Replace bold to italic in google docs using apps script

How to achieve a find and replace a bold font to italic using app script for Google docs. Note that it has to replace only the bold ones to italic and not all the text.

Say. A sample text

A quick brown fox jumps over a lazy dog a quick brown fox jumps over a lazy dog a quick brown fox jumps over a lazy dog.

Upvotes: 3

Views: 4644

Answers (2)

Joter
Joter

Reputation: 316

Use getTextAttributeIndices of Text class.


function myFunction() {
  var doc = DocumentApp.getActiveDocument()
  var paragraphs = doc.getBody().getParagraphs()
  for(p of paragraphs) {
    var text = p.editAsText();
    var idxs = text.getTextAttributeIndices();
    var offset = 0
    var endOffset = (i + 1 < idxs.length ? idxs[i + 1] : text.getText().length)
    if (endOffset == 0) {
      continue
    }
    for (var i = 0; i < idxs.length; i++) {
      offset = idxs[i]
      endOffset = (i + 1 < idxs.length ? idxs[i + 1] : text.getText().length)
      var str = text.getText().substring(offset, endOffset)
      var link = text.getLinkUrl(offset)
      var isBold = text.isBold(offset)
      var color = text.getForegroundColor(offset)
      if (isBold) {
        Logger.log("(" + offset + "," + endOffset + ") isBold:" + isBold + " color:" + color + " link:" + link + " text:" + str + "")
        var endOffsetInclusive = endOffset - 1
        text.setBold(offset, endOffsetInclusive, false)
        text.setItalic(offset, endOffsetInclusive, true)

      }
    }
  }
}

Upvotes: 2

user3717023
user3717023

Reputation:

This is slightly awkward because there is nothing like "text node in bold" in Google Documents; the Text element does not have much internal structure. The solution seems to be to loop over its characters and test each on being bold. When the ranges of bold text are identified in the loop, they are set to italic with setItalic method. At the end, bold is removed from all text.

function bold2italic() {  
  var doc = DocumentApp.getActiveDocument();
  var text = doc.getBody().editAsText();
  var startBold = 0;
  var bold = false; 
  for (var i = 0; i < text.getText().length; i++) {
    if (text.isBold(i) && !bold) {
      startBold = i;
      bold = true;
    }
    else if (!text.isBold(i) && bold) {
      bold = false;
      text.setItalic(startBold, i-1, true);
    }
  }
  if (bold) {
    text.setItalic(startBold, i-1, true);
  }  
  text.setBold(false);
}

Upvotes: 6

Related Questions