Skip to main content
Participant
January 31, 2020
Question

Python Indesign script _ How to insert a picture into a page and autofit the size?

  • January 31, 2020
  • 2 replies
  • 2062 views

I need to find a way to insert pictures into an InDesign project through a python script. But the code doesn't work.

myPage = myDocument.Pages.Item(1)
myRectangle = myPage.Rectangles.Add()
myRectangle.GeometricBounds = [7, 1, 9, 7] import matplotlib.image as mpimg
import matplotlib.pyplot as plt img_path = r'C:\...\In-Design Project\AA.jpg'img = mpimg.imread(img_path)
img = mpimg.imread(img_path)
myRectangle.Place(img) **# Error**

The error is :

com_error: (-2147352567, 'Exception occurred.', (35869, 'C:\\Program Files\\Adobe\\Adobe InDesign 2020\\InDesign.exe', 'Cannot create the link resource from the given URI.', None, 0, 0), None)

 

I found some functions that might be helpful as below but still haven't found a solution

 

Whether the picture is inserted into an existed frame or into a new frame doesn't matter. I just really need a feasible way to achieve it. Thanks.

This topic has been closed for replies.

2 replies

Peter Kahrel
Community Expert
Community Expert
February 3, 2020

In

myRectangle.Place(img)

'img' must be a file object. I don't know if that's the case in your script.

Participant
February 26, 2020

Thanks Peter! But do you know how to read in an image as a File object in python? Thanks.

Peter Kahrel
Community Expert
Community Expert
February 26, 2020

No, I don't. You'd have to check in the Python documentation. It's probably something like

img = File ('C:\...\In-Design Project\AA.jpg')

or

img = new File ('C:\...\In-Design Project\AA.jpg'i)

Another thing: mind the backslashes. Either escape them ('c:\\dir') or use forward slashes ('c:/dir'). Again, there's lots of Python documentation around.

brian_p_dts
Community Expert
Community Expert
January 31, 2020

I don't know the first thing about Python scripting for InDesign, but from what I can tell 

mpimg.imread(img_path)

returns an array of the image data it read. Rectangle.place() needs a File object to place in its first argument. Not sure how you would return a Javascript File object from Python, but that's where I'd investigate. It could be just as simple as creating one out of your img path. Also looks like you are calling img = mpimg.imread(img_path) twice; once in its own line and once in the line above it at the end. That might also be causing problems. 

Participant
February 26, 2020

Great thanks. Currently what within Rectangle.place() is not a File object. Do you know how to read in an image as a File object in python? Thanks.

brian_p_dts
Community Expert
Community Expert
February 26, 2020

Not sure. You could try: 

 

myRectangle.Place('C:\...\In-Design Project\AA.jpg')

 

You could also open the path:

 

fileobj = ('C:\...\In-Design Project\AA.jpg','r')

myRectangle.Place(filobj)