Image duplicates itself when using appendParagraph in Google Script

久未见 提交于 2019-12-25 01:27:42

问题


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();

}

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?


回答1:


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();

}


来源:https://stackoverflow.com/questions/55597075/image-duplicates-itself-when-using-appendparagraph-in-google-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!