1

I wrote a script to add an image from my Google Drive and some custom text to a Google Doc. (I got the image insertion code from here). The resulting document is created ok, but my image is added twice for some reason...

function myFunction(e) {

  var doc = DocumentApp.create('fileTest');
  var body = doc.getBody();

   var matchedFiles = DriveApp.getFilesByName('logo.png');
   if (matchedFiles.hasNext()) {
    var image = matchedFiles.next().getBlob(); 
     var positionedImage = body.getParagraphs()[0].addPositionedImage(image);
   }

  body.appendParagraph('Test line of text for testing');

  doc.saveAndClose();

}

resulting document

However, if I get rid of my appendParagraph code (body.appendParagraph(t1);) I only get one image (but obviously without the paragraph of text I want)

What's going on here? And how do I add both one picture and my paragraph of text?

theforestecologist
  • 4,667
  • 5
  • 54
  • 91
  • I've tried on two different machines, 2 different browsers, I've changed both the image and the text, and I've tried numerous variations of this approach, but they all result in the same duplication issue!! -_- ...can anybody help me out here?? – theforestecologist Apr 09 '19 at 17:24
  • What if you comment out the line that starts var positionedImage? – J. G. Apr 09 '19 at 17:25
  • @J.G. then no image shows up at all. – theforestecologist Apr 09 '19 at 17:28
  • I believe this is due to natural inheritance of formatting. When working on my [answer here](https://stackoverflow.com/a/54775009/9337071) I noticed that the previous element's formatting was applied to the next element by default. So, your new paragraph inherits the image as a part of its formatting. Yikes. – tehhowch Apr 10 '19 at 11:55

1 Answers1

3

I have not even the slightest clue as to why, but I found a way to make this work.

Switching the order of my code seemed to do the trick. I simply moved the image-insertion code to the end (i.e., after the appendParagraph code), and it worked fine. No duplicate image!

function myFunction(e) {

  var doc = DocumentApp.create('fileTest');
  var body = doc.getBody();

  body.appendParagraph('Test line of text for testing');

   var matchedFiles = DriveApp.getFilesByName('logo.png');
   if (matchedFiles.hasNext()) {
    var image = matchedFiles.next().getBlob(); 
     var positionedImage = body.getParagraphs()[0].addPositionedImage(image);
   }

  doc.saveAndClose();

}
theforestecologist
  • 4,667
  • 5
  • 54
  • 91
  • It seems that when you add the image in your previous code it adds the image to empty - an automatically created paragraph at begining of a body element and when you add the next paragraph with the actual text it copies formatting from previous paragraph (the one with picture) also with the picture (as part of formating). So when you first add a text and then attach picture to it, then there is only one paragraph with text and added image to it. – Jindřich Širůček Oct 26 '21 at 03:20