How to open a text file using Javascript from Adobe Indesign CS4?

lecter picture lecter · Aug 30, 2009 · Viewed 12.3k times · Source

How can I open a text file, read the contents, and then insert the contents into a document in InDesign?

Answer

Josh Voigts picture Josh Voigts · Dec 7, 2012

Here's an example of reading a file from InDesign. If you want to write to a file as well, you will need to open the file in write mode w instead.

// Choose the file from a dialog
var file = File.openDialog();

// Or use a hard coded path to the file
// var file = File("~/Desktop/hello world.txt");

// Open the file for reading
file.open("r");

// Get the first text frame of the currently active document
var doc = app.activeDocument;
var firstTextframe = doc.pages[0].textFrames[0];

// Add the contents of the file to the text frame
firstTextframe.contents += file.read();

Here is a link to the File object's documentation online. You can also find the rest of InDesign's scripting DOM documentation here.