InDesign MY-NOTEBOOK

Saturday, February 16, 2008

スクリプトによるテーブルの生成その1 ( InDesign CS5 )

まずは手始めにスクリプトで 5x5 のテーブルを作成します。InDesignのテーブルはセルの結合などのややこしい話がなければとても扱いやすくできています。

helloTable.jsx

//
// InDesign CS5 ,テーブルを作成
//

var doc   = createNewDoc();
var page  = getFirstPage( doc );
var tf    = createTextFrame( page );
var table = createTable( tf );




function createNewDoc(){ 
	return app.documents.add();
}
function getFirstPage( doc ){
	return doc.pages.item(0);
}
function createTextFrame( page ){
	var tf = page.textFrames.add();
	tf.geometricBounds = getBounds(page);
	return tf;
}
function createTable( tf ){
	//
	// create a table(5x5) object in the textframe
	//
	var table=tf.tables.add();
	table.columnCount = 5;
	table.bodyRowCount = 5;

	//
	// calc table cell size
	//
	var bounds = tf.geometricBounds;

	var gap=1;
	var w=bounds[3]-bounds[1]-gap;
	var h=bounds[2]-bounds[0]-gap;
	var cellW=w/table.columnCount;
	var cellH=h/table.bodyRowCount;

	//
	// set up size to cells
	//
	for(var i=0; i<table.bodyRowCount; i++){
	    var row=table.rows.item(i);
	    for(var j=0; j<table.columnCount; j++){
	        var cell=row.cells.item(j);
	        cell.width=cellW;
	        cell.height=cellH;
	        cell.contents="Hello ("+i+","+j+")";
	    }
	}

	return table;
}

// Page の親が Document ではなく Spread などの場合がある点に注意.
function getDocFromPage( page ){
	var obj = page.parent;
	if( (obj instanceof Document)==false ){
		obj = obj.parent; 
	}
	return obj;
}

// マージンを考慮したページの bounds を取得.
function getBounds( page ){

	var doc = getDocFromPage( page );
	var pH = doc.documentPreferences.pageHeight;
	var pW = doc.documentPreferences.pageWidth;

	return [
		page.marginPreferences.top,
		page.marginPreferences.left,
		pH - page.marginPreferences.bottom, 
		pW - page.marginPreferences.right
	];
}



InDesign CS5 でテストしています。

InDesign CS5 では Page インスタンスの親( aPage.parent )がDocument以外のインスタンスがくる場合もあるので注意が必要です。CS3では確か常に Document だったような気がしたのですが。