Como sugiere el título, estoy tratando de encontrar el índice de un elemento de texto de marcador de posición en una tabla de documentos de Google para poder reemplazarlo con texto almacenado en un documento diferente.
Puedo obtener el texto preformateado que se agregará al documento, no el lugar requerido en la tabla, usando otros ejemplos que encontré en stackoverflow.
Sin embargo, no tengo claro cómo encontrar el índice del elemento de marcador de posición dentro de una de las muchas tablas en el documento de plantilla.
Necesito el índice del texto del marcador de posición para poder usar la función insertParagraph.
Para agregar un poco más de detalle: puedo encontrar el texto del marcador de posición e insertar una imagen usando el siguiente código.
function replaceTextToImage(body, searchText, image, width) { var next = body.findText(searchText); if (!next) return; var r = next.getElement(); r.asText().setText(""); var img = r.getParent().asParagraph().insertInlineImage(0, image); if (width && typeof width == "number") { var w = img.getWidth(); var h = img.getHeight(); img.setWidth(width); img.setHeight(width * h / w); } return next;};
Sin embargo, necesito conservar el formato del documento que quiero importar. Así que abro el documento con el texto formateado y luego recorro los diferentes tipos de elementos con un condicional para insertar el texto/imagen si el tipo de elemento coincide. Es por eso que necesito el índice del texto del marcador de posición. Consulte la función a continuación:
function replaceTextWithDoc(body, searchText, id) { let doc = DocumentApp.openById(id) var numElements = body.getNumChildren(); var index = numElements; for (var i = 0; i < numElements; i++) { var child = body.getChild(i); if (child.asText().getText() == searchText){ index = i; body.removeChild(child); break; } } var totalElements = doc.getNumChildren(); for( var j = 0; j < totalElements; ++j ) { var element = doc.getChild(j).copy(); var type = element.getType(); if( type == DocumentApp.ElementType.PARAGRAPH ) body.insertParagraph(index, element); else if( type == DocumentApp.ElementType.TABLE ) body.insertTable(index, element); else if( type == DocumentApp.ElementType.LIST_ITEM ) body.insertParagraph(index, element); else throw new Error("According to the doc this type couldn't appear in the body: "+type); } }Este es un ejemplo del texto de marcador de posición ( {iText} ) en una tabla: https://docs.google.com/document/d/1mZWpQqk4gYAF6UCRALrT8S99-01RYNfwni_kqDzOg7E/edit?usp=sharing
Aquí hay un ejemplo de texto e imágenes con las que necesito reemplazar el texto del marcador de posición, manteniendo todo/cualquier formato. https://docs.google.com/document/d/1wuX0g5W2GL0YJ7admiv3TNEepb_zVwQleKwazCiAMBU/edit?usp=sharing
Si lo entiendo correctamente, desea copiar el contenido de un documento (compuesto por texto e imágenes en línea) en ciertas celdas de la tabla que contienen un determinado texto de marcador de posición.
En ese caso, te sugiero lo siguiente:
const PLACEHOLDER = "{iText}"; function myFunction() { const doc = DocumentApp.openById(TARGET_ID); const sourceDoc = DocumentApp.openById(SOURCE_ID); const body = doc.getBody(); const tables = body.getTables(); tables.forEach(table => { const numRows = table.getNumRows(); for (let i = 0; i < numRows; i++) { const row = table.getRow(i); const numCells = row.getNumCells(); for (let j = 0; j < numCells; j++) { const cell = row.getCell(j); const cellText = cell.editAsText(); const text = cellText.getText(); if (text.includes(PLACEHOLDER)) { cell.clear(); appendSourceContent(sourceDoc, cell); } } } }); } function appendSourceContent(doc, cell) { const numChildren = doc.getNumChildren(); for (let j = 0; j < numChildren; j++) { const element = doc.getChild(j).copy(); const type = element.getType(); if (type == DocumentApp.ElementType.PARAGRAPH) { cell.appendParagraph(element); } else if (type == DocumentApp.ElementType.INLINE_IMAGE) { cell.appendImage(element); } } }else if adicionales si el contenido de origen puede tener tipos de elementos diferentes a los de los ElementTypes y las imágenes en línea.