Updating / replacing an embedded image in a Google document

I am trying to install a function for updating images in a Google Doc, just like the Lucidchart add-on above its "Updated inserted chart" function. To do this, I follow these steps:

  • Create a named range and save its document property identifier along with data to create an image for later retrieval.
  • When updating, call body.getNamedRangeById () and replace the element with the new generated image.

This works, but I have the following issues that do not happen with Lucidchart:

  • Each update after an empty line is added an empty line.
  • If the user drags the image inside the document to reposition it, the named range disappears, and I cannot get it later.
  • If the user centralized the image, after updating the image returns to the left position, even copying its attributes

Does anyone know a good strategy for replacing / updating a link image in Google Docs, does the Lucidchart add-in update feature work as well?

thank

+4
source share
2 answers

NamedRanges are really lost when moving the range, so they are not very good for your scenario. But there is no other way to identify elements (which is a big mistake of Google Docs).

LINK_URL , , -, Lucidchart. , .

, ( - ) , . , , .

:

function initialInsert() {
  var data = Charts.newDataTable().addColumn(
    Charts.ColumnType.STRING, 'Fruits').addColumn(
    Charts.ColumnType.NUMBER, 'Amount').addRow(
    ['Apple',15]).addRow(
    ['Orange',6]).addRow(
    ['Banana',14]).build();
  var chart = Charts.newPieChart().setDataTable(data).build();

  var body = DocumentApp.getActiveDocument().getBody()
  body.appendImage(chart).setLinkUrl('http://mychart');
  //here we're inserting directly in the body, a wrapping paragraph element will be created for us
}

function updateImage() {
  var data = Charts.newDataTable().addColumn(
    Charts.ColumnType.STRING, 'Fruits').addColumn(
    Charts.ColumnType.NUMBER, 'Amount').addRow(
    ['Apple',Math.floor(Math.random()*31)]).addRow( //random int between 0 and 30
    ['Orange',Math.floor(Math.random()*31)]).addRow(
    ['Banana',Math.floor(Math.random()*31)]).build();
  var chart = Charts.newPieChart().setDataTable(data).build();

  var img = getMyImg(DocumentApp.getActiveDocument().getBody(), 'http://mychart');
  //let insert on the current parent instead of the body 
  var parent = img.getParent(); //probably a paragraph, but does not really matter
  parent.insertInlineImage(parent.getChildIndex(img)+1, chart).setLinkUrl('http://mychart');
  img.removeFromParent();
}

function getMyImg(docBody, linkUrl) {
  var imgs = docBody.getImages();
  for( var i = 0; i < imgs.length; ++i )
    if( imgs[i].getLinkUrl() === linkUrl )
      return imgs[i];
  return null;
}

link_url, , , , Lucidchart, . .

+4

PlantUML Gizmo.

, , :

function insertImage(imageDataUrl, imageUrl) {
  /*
   * For debugging cursor info
   */
//  var cursor = DocumentApp.getActiveDocument().getCursor();
//  Logger.log(cursor.getElement().getParent().getType());
//  throw "cursor info: " + cursor.getElement().getType() + " offset = " + cursor.getOffset() + " surrounding text = '" + cursor.getSurroundingText().getText() + "'  parent type = " + 
//    cursor.getElement().getParent().getType();
  /*
   * end debug
   */
  var doc = DocumentApp.getActiveDocument();
  var selection = doc.getSelection();
  var replaced = false;
  if (selection) {
    var elements = selection.getSelectedElements();
    // delete the selected image (to be replaced)
    if (elements.length == 1 &&
        elements[0].getElement().getType() ==
        DocumentApp.ElementType.INLINE_IMAGE) {
          var parentElement = elements[0].getElement().getParent();  // so we can re-insert cursor
          elements[0].getElement().removeFromParent();
          replaced = true;
          // move cursor to just before deleted image
          doc.setCursor(DocumentApp.getActiveDocument().newPosition(parentElement, 0));
     } else {
          throw "Please select only one image (image replacement) or nothing (image insertion)"
     }
  }
  var cursor = doc.getCursor();
  var blob;

  if (imageDataUrl != "") {
    blob = getBlobFromBase64(imageDataUrl);
  } else {
    blob = getBlobViaFetch(imageUrl);
  }

  var image = cursor.insertInlineImage(blob);  

  image.setLinkUrl(imageUrl);

  // move the cursor to after the image
  var position = doc.newPosition(cursor.getElement(), cursor.getOffset()+1);
  doc.setCursor(position);

  if (cursor.getElement().getType() == DocumentApp.ElementType.PARAGRAPH) {
    Logger.log("Resizing");
    // resize if wider than current page
    var currentParagraph = DocumentApp.getActiveDocument().getCursor().getElement().asParagraph();
    var originalImageWidth = image.getWidth();  // pixels
    var documentWidthPoints = DocumentApp.getActiveDocument().getBody().getPageWidth() - DocumentApp.getActiveDocument().getBody().getMarginLeft() - DocumentApp.getActiveDocument().getBody().getMarginRight();
    var documentWidth = documentWidthPoints * 96 / 72;  // convert to pixels (a guess)
    var paragraphWidthPoints = documentWidthPoints - currentParagraph.getIndentStart() - currentParagraph.getIndentEnd();
    var paragraphWidth = paragraphWidthPoints * 96 / 72;  // convert to pixels (a guess)

    if (originalImageWidth > paragraphWidth) {
      image.setWidth(paragraphWidth);
      // scale proportionally
      image.setHeight(image.getHeight() * image.getWidth() / originalImageWidth);  
    }

  }

}
+2

All Articles