user11837850
user11837850

Reputation: 1

need to copy an image from a doc to another with Google Script

I'm trying to copy an image from a google doc "template" and paste in another doc with script. Already search for some solutions in web but none worked for me. Here's my code, this is getting an invalid image data error.

function creatingLabels(link, document, model, labelTemplate) {
    var headerLabel = labelTemplate.getBody().getImages();

    Logger.log(headerLabel.toString());
    Logger.log(headerLabel);

    var textLabel = labelTemplate.getBody().getText();

    var text = textLabel.replace(' %LOCAL%', model);

    var QrCode = getImageFromURL(link);

    document.getBody().insertImage(1, headerLabel)
    labelTemplate.getBody().setText(text);
    labelTemplate.getBody().insertImage(1, QrCode);
}

function getImageFromURL(link) {
    var url = encodeURI(link)

    return UrlFetchApp.fetch(url, { muteHttpExceptions: true });
}

Upvotes: 0

Views: 575

Answers (1)

Cooper
Cooper

Reputation: 64052

This function copies an image from one document and creates another document and appends the image to the new document. It also displays the image on a dialog. If your looking for the image and can't find it, then look in your root folder.

function copyImage() {
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  var images=body.getImages();
  var image=images[0];
  var b64Url='data:' + image.getBlob().getContentType() + ';base64,' + Utilities.base64Encode(image.getBlob().getBytes());
  var html=Utilities.formatString('<img src="%s" width="640" height="480" />',b64Url);
  var userInterface=HtmlService.createHtmlOutput(html).setWidth(700).setHeight(550);
  DocumentApp.getUi().showModelessDialog(userInterface, 'Images');
  var doc1=DocumentApp.create('SO2');
  doc1.getBody().appendImage(image.getBlob());
  var image=doc1.getBody().getImages()[0];
  image.setWidth(640);
  image.setHeight(480);
  doc1.saveAndClose();
}

Upvotes: 1

Related Questions