how can I extract text from indd files or indesign files using python programs?

1.2k Views Asked by At

I need to create an api where user will provide indesign file and I need to extract text from it.

1

There are 1 best solutions below

0
On

Basically it can be done this way:

from win32com.client import Dispatch

app = Dispatch('InDesign.Application.CS6')
doc = app.Open(r"d:\text.indd")
contents = ""
for story in doc.stories: contents += story.contents + "\n"
f = open(r"d:\text.txt", "w", encoding="utf8")
f.write(contents)
f.close()
doc.Close()

But perhaps there can be glitches with special symbols. I believe it makes sense to use the native Javascript Extendscript for this task. Something like this:

var doc = app.open(File("d:/text.indd"));
var stories = doc.stories.everyItem().getElements();
var contents = "";
for (var i=0; i<stories.length; i++) contents += stories[i].contents + "\n";
var file = File("d:/text.txt");
file.open("w");
file.write(contents);
file.close();
doc.close();