1

I'm trying to place an image against the right-hand margin of a google doc using scripts. I've got this calculation for the left offset:

body.getPageWidth()-body.getMarginRight()-body.getMarginLeft()-myImage.imageWidth

This consistently places the image 5/8 of an inch inside the margin. I thought maybe this might be something to do with the automatic margin around a wrapped image? I can't find a way to control that in the PositionedImage documentation though.

Is there an extra element I'm missing in my calculation for the left offset? Something else I'm failing to allow for? Is there another method I can use to place the image?

1 Answers1

1

Is the image already a PositionedImage - was it moved to a PositionedImage? or is there a choice? If it is an InlineImage; Then you can getParent() and setAttributes() LEFT_TO_RIGHT. It will re-position against the right margin.

function imgRight() {
  var doc = DocumentApp.getActiveDocument()
  var body = doc.getBody()
  // Get the first inline image in the doc.body
  var img_container = body.getImages()[0].getParent()

  // Set the ContainerElement to right_to_left
  img_container.setAttributes({LEFT_TO_RIGHT:false})
}

edit and update: The issue with the calculation for PositionedImage.LeftOffset is that the image.getWidth() returns the width in pixels and the margins and page size in points. Convert the img pixels to points and the offset calculation would look something like:

var body = DocumentApp.getActiveDocument().getBody();
var body_attributes = body.getAttributes();

var img = body.getParagraphs()[0].getPositionedImages()[0];
var img_width = img.getWidth();
var img_in_points = img_width * 72/96;
var current_img_offset = img.getLeftOffset();

var offset = body_attributes.PAGE_WIDTH - body_attributes.MARGIN_RIGHT - body_attributes.MARGIN_LEFT  - img_in_points + current_img_offset;
random-parts
  • 2,137
  • 2
  • 13
  • 20
  • Thanks! It does need to be a PositionedImage - to wrap text. If I do this and then convert to a PositionedImage though, would it retain it's position? – Briony Doyle Nov 15 '17 at 17:54
  • updated code - have to convert the image width to points as that is what the margin and page size returns – random-parts Nov 15 '17 at 23:58