Search code examples
google-apps-scriptgoogle-docs

How to erase positioned images from Google Documents?


I'm trying to create a function which erases everything in a Google Document.

My code so far, which goes as follows, gets rid of everything, except for positioned images.

// clears document
function eraseContent(){ 
  var body = DocumentApp.getActiveDocument().getBody();
  
  body.clear();

  // Remove all images in the document body.
  var imgs = body.getImages();
  for (var i = 0; i < imgs.length; i++) {
  imgs[i].removeFromParent();
  }
}

Most of this code comes from here.

What can I do to erase positioned images from my document?


Solution

  • In the current stage, unfortunately, there are no methods for deleting the positioned images in Class PositionedImage, yet. But when Google Docs API is used, the positioned images can be deleted. So how about this modification? The flow of this modified script is as follows.

    1. Retrieve paragraphs.
    2. Retrieve the object IDs of the positioned images.
    3. Create request body for the method of batchUpdate in Google Docs API using the retrieved object IDs.
    4. Delete the positioned images.

    In order to use the sample script, before you run the script, please enable Google Docs API at Advanced Google Services and API console as follows.

    Enable Google Docs API at Advanced Google Services

    • On script editor
      • Resources -> Advanced Google Services
      • Turn on Google Docs API v1

    Enable Google Docs API at API console

    • On script editor
      • Resources -> Cloud Platform project
      • View API console
      • At Getting started, click "Explore and enable APIs".
      • At left side, click Library.
      • At "Search for APIs & services", input "Docs". And click "Google Docs API".
      • Click Enable button.
      • If API has already been enabled, please don't turn off.

    Modified script:

    Please replace eraseContent() as follows and run it.

    function eraseContent(){
      var doc = DocumentApp.getActiveDocument();
      var body = doc.getBody();
      body.clear();
    
      // Retrieve paragraphs.
      var paragraphs = body.getParagraphs();
    
      // Retrieve the object IDs of the positioned images.
      // Create request body for the method of batchUpdate in Google Docs API using the retrieved object IDs.
      var requests = paragraphs.reduce(function(ar, e) {
        return ar.concat(e.getPositionedImages().map(function(f) {
          return {deletePositionedObject: {objectId: f.getId()}}
        }));
      }, []);
    
      // Delete the positioned images.
      if (requests.length > 0) {
        Docs.Documents.batchUpdate({requests: requests}, doc.getId());
      }
    }
    

    References:

    If I misunderstood your question, I apologize.