I am currently developing a script that allows teachers to easily create translations of documents stored on Google Drive. The script is expected to go through the body elements of the document, translate the text, and paste it onto a new page appended to the document. It should also be able to identify images and include them in the translated document.
While I have successfully implemented text translation - where paragraph text is translated and copied to a new page - I am facing issues with copying images from the document.
Script
function translate() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
body.appendPageBreak();
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 ){
var text = element.asParagraph().getText();
var spn = LanguageApp.translate(text, 'en', 'es');
body.appendParagraph(spn);
}
else if( type == DocumentApp.ElementType.INLINE_IMAGE ){
var img = element.asInlineImage().getBlob();
body.appendImage(img);
}
}
}
During my research, I came across this Stack Overflow post which helped me print the elements of the document in the console, aiding my logic. The test script in the post includes a paragraph with an INLINE_IMAGE
, but my script is not successfully copying it to the new page. The text, however, is being translated correctly.
Do you think I need to implement a different approach in the logic to handle images along with text?