Replace image with table in google doc

2019-07-31 19:16发布

问题:

I want to replace a selected image with a table containing that image in a Google Doc. No table is inserted into the google doc when I run the code.

    function insertImage(ID, caption) {
    var selection = DocumentApp.getActiveDocument().getSelection();
    if (selection) {
        var elements = selection.getSelectedElements();
        var tImg = elements[0].getElement();
        var cells = [
            [tImg.asInlineImage(), ID+': '+caption]
        ];
        var parentElement = tImg.getParent();
        parentElement.insertTable(parentElement.getChildIndex(tImg) + 1, cells)
        tImg.removeFromParent();
    }
}

The image isn't removed and the table isn't added. Thanks!

回答1:

  • You want to replace an selected image to a table.
  • You want to the selected image to the 1st column of cell of the inserted table. the text is put in the 2nd column.

If my understanding of your question is correct, how about this modification?

Modification points:

  • Method of insertTable() is the method of Class Body.
  • The place of image is required to be retrieved as the child index of the document body.
  • Image is inserted to the cell of the inserted table after the table was inserted.
  • In this modification, when the image is deleted, it deletes the paragraph of image. By this, the image can be replaced to the table without including the line break. This situation is the same with inserting the image in the cell.
  • getSelectedElements() was deprecated. So please use getRangeElements().

When above points are reflected to the script, it becomes as follows.

Modified script:

function insertImage(ID, caption) {
//  ID = "sample ID"; // for sample
//  caption = "sample caption"; // for sample

  var doc = DocumentApp.getActiveDocument(); // Added
  var body = doc.getBody(); // Added
  var selection = doc.getSelection(); // Modified
  if (selection) {
    var elements = selection.getRangeElements(); // Modified
    var e = elements[0].getElement(); // Modified
    if (e.getType() == DocumentApp.ElementType.INLINE_IMAGE) { // Added
      var tImg = e.asInlineImage(); // Modified
      var parentElement = tImg.getParent();
      var cells = [["", ID + ': ' + caption]]; // Modified
      var table = body.insertTable(body.getChildIndex(parentElement), cells); // Modified
      var cell = table.getCell(0, 0); // Added
      cell.insertImage(0, tImg.getBlob()).getParent().asParagraph().getNextSibling().removeFromParent(); // Added
      tImg.getParent().asParagraph().removeFromParent(); // Modified
    }
  }
}
Input:

Output:

Note:

  • In your script, the 1st image of selected elements is used. So I followed to this.

References:

  • insertTable()
  • insertImage()
  • getRangeElements()

If this was not what you want, please tell me. I would like to modify it.