I used the following snippet to insert an image into a Google Document:
http://stackoverflow.com/a/18859986/1536038
var doc = DocumentApp.openById('Google Drive Id');
var img = DriveApp.getFileById('Google Drive Id').getBlob();
doc.getBody().insertImage(0, img);
The result is an In line
image:
I want, however, to have a Wrap text
image, like so:
Is that possible via Google Apps Script (on the fly)?
Issue 1529 has been fixed. As of December 2015, Google Apps Script can manipulate
PositionedImage
objects in Google Docs.They behave a little differently than
InlineImage
elements, as they need to be anchored to a ListItem or Paragraph element, whileInlineImages
can be added only toBody
,FooterSection
,HeaderSection
orTableCell
elements.A
PositionedImage
is an object anchored in an element, while anInlineImage
is itself an element of a document. This implies that you cannot convert one type of image directly to the other. (When you switch an image from "Wrap text" to "Inline" using the UI, thePositionedImage
is removed from its anchor paragraph, then inserted into the body of the document outside of that paragraph. You could emulate that via script if necessary.)Insert a
PositionedImage
Here's an example of a
PositionedImage
inserted by the following script:The log shows the ID of the new image, like this:
Be careful - if you add multiple images to the same element (e.g. Paragraph), with default layout, the newest image will overlay existing ones. Therefore, it may look like you have a single image when there are actually a pile of them.
Retrieve existing
PositionedImage
sSince a
PositionedImage
is not an element of a document, it does not appear in the element hierarchy with elements like paragraphs, tables, or InlineImages, and cannot be found through the document methodsgetChild()
,getNextSibling()
, and so on. Likewise, there is noBody.getPositionedImages()
to parallelBody.getImages()
.Instead, you can get a
PositionedImage
using its unique ID, e.g.kix.9dwnzjfapdy8
from the earlier example.Alternatively, you can get all the
PositionedImage
objects in a containing element as an array.Retrieving all the
PositionedImage
s in a document requires traversing all the possible anchor elements. The following utility does just that.Layout control
Most of the layout controls for
PositionedImages
are well described in the documentation:setHeight()
,getHeight()
setWidth()
,getWidth()
setLeftOffset()
,getLeftOffset()
setTopOffset()
,getTopOffset()
setLayout()
,getLayout()
The
PositionedLayout
enum used with the Layout methods is unique toPositionedImages
. At the time of launch of PositionedImage support however, it was not included in editor autocompletion, and the documentation contained no examples of its use. Let's fill that gap.Here's how you can set the layout of a
PositionedImage
so that it is wrapped by text:The following utility function gets the English equivalent of a
PositionedLayout
enum.Note: This has been concurrently posted on my blog.