Skip to content

Instantly share code, notes, and snippets.

@bennettscience
Last active August 29, 2015 14:27
Show Gist options
  • Save bennettscience/066b7eec14b9c8c61eee to your computer and use it in GitHub Desktop.
Save bennettscience/066b7eec14b9c8c61eee to your computer and use it in GitHub Desktop.
docTranslate.gs
// This function converts a document from English to Spanish quickly.
// The post from http://stackoverflow.com/questions/25509159/how-i-can-get-the-textwrap-image-in-google-doc/25509591#25509591
// was helpful for creating the logic to check for images in the document.
function translate() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
// Add a page break for the translated material.
body.appendPageBreak();
// Get the number of elements in the document
var elements = body.getNumChildren();
// Use the number to loop through each element in the document.
for( var i=0;i<elements;i++) {
var element = body.getChild(i).copy();
var type = element.getType();
// Test each type for a child element and run script based on the result
// Images are nested in a paragraph as a child, so the second `if` makes
// sure there is no image present before moving to the next paragraph.
if( type == DocumentApp.ElementType.PARAGRAPH ){
if(element.asParagraph().getNumChildren() !== 0 && element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) {
var img = element.asParagraph().getChild(0).asInlineImage().getBlob();
body.appendImage(img);
} else if(element.asParagraph().getNumChildren() !== 0 && element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_DRAWING) {
var drawing = element.asParagraph().copy();
body.appendParagraph(drawing);
} else {
var text = element.asParagraph().getText();
var spn = LanguageApp.translate(text, 'en', 'es');
body.appendParagraph(spn);
} // end the paragraph loop for child elements.
// Tables are top-level, so they get their own statement outside the
// paragraph loop above.
} else if(type == DocumentApp.ElementType.TABLE) {
element.asTable().copy();
body.appendTable(element);
} else if(type == DocumentApp.ElementType.LIST_ITEM) {
var list = element.asListItem().getText();
body.appendListItem(LanguageApp.translate(list, 'en', 'es'));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment