I created some simple code that pulls a Google Doc URL from a spreadsheet in cell B2. The code works for some documents, but not others.
The program correctly creates a duplicate of the doc, which preserves all formatting. From there, I aim to replace the English text with Spanish.
I run into errors with Http:// links and some documents fully reformat, others do not.
Suggestions?
//This function works to create a nearly perfect copy of the document from English to Spanish. Problems with URLs and some long docs.
function spanishConverter() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); //bound to Google Sheet
var listDoc = ss.getSheetByName('Doc List'); //SpreadSheet Page
var docEng = listDoc.getRange(2,2).getValue(); //Cell pulling URL from
var currentDoc = DocumentApp.openByUrl(docEng); //Opens the English version from URL on SpreadSheet
var docName = currentDoc.getName();
var docId = currentDoc.getId();
var newDoc = DriveApp.getFileById(docId).makeCopy('Spanish ' + docName).getUrl(); //Opens and makes a copy and captures URL
var newSp = DocumentApp.openByUrl(newDoc);
var body = newSp.getBody();
var paragraphs = body.getParagraphs();
//This script loops throught the paragraphs
for(var i=0; i<paragraphs.length; i++)
{
var text = paragraphs[i].getText(); //pulls text per paragraph
var transText = LanguageApp.translate(text, 'en', 'es');
Logger.log([text,transText]);
if (text !== "") //skips blanks
{
body.replaceText(text, transText);
}
}
}
This is the full solution. HTML links are skipped unless they are interpreted as a text element.