Stemming from a previous question, I'm creating an Add On for Google Docs which takes the body of a document and translates it as a new page in the same doc. I have the script running and it's translating correctly, but I'm having trouble with the logic to keep the formatting.
This post from last year works well when copying elements in the same language. But, the LanguageApp
in Google requires a string
to translate.
I simplified the script linked above to copy a document within itself:
function simpleTranslate() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
Logger.log(body.getAttributes());
var elements = body.getNumChildren();
for (var i = 0; i<elements; ++i) {
var element = body.getChild(i).copy();
var type = element.getType();
if(type == DocumentApp.ElementType.PARAGRAPH) {
// This block copies formatting correctly
// Pastes English and Spanish into the doc (see img 1).
body.appendParagraph(element);
var spn = LanguageApp.translate(element.getText(), 'en', 'es');
body.appendParagraph(spn);
// This block pastes Spanish only with no formatting (see img 2)
// This block is normally commented out when the script runs for testing
var spn = LanguageApp.translate(element.getText(), 'en', 'es');
body.appendParagraph(spn)
}
}
}
Img1 - text formats correctly, pastes both English and Spanish
Img1 http://www.brianbennett.org/images/coderesult1.png
Img2 - removing the English append, Spanish still translates but loses formatting because of string
requirement.
Img2 http://www.brianbennett.org/images/coderesult2.png
I would like help with the logic within the function. I'm thinking the only way to do this - because of the string
requirement - is to go line by line, copying the English, translating on a new line, then removing the English. Is there a better way to translate the text and keep the formatting?