Skip to main content
brown1982
Participating Frequently
October 12, 2022
Question

Error: target.parent.documentOffset;

  • October 12, 2022
  • 1 reply
  • 166 views

Error with scripting, who can help!?

I have a script that imports all documents from 1 folder, but for some reason it blocks -> 'crash' and gives this error.

 

This is an old script from CS4 time, I think it has to do with CC 2022 being something different now. Can someone have a look and help with this?

 

Many thanks in advance!

if (app.activeDocument.saved)
{
	var myFileLocation = Folder.selectDialog("Selecteer map met files", app.activeDocument.filePath);
	if (myFileLocation == null)
		exit(0);
} else
{
	var myFileLocation = Folder.selectDialog("Selecteer map met files");
	if (myFileLocation == null)
		exit(0);
}


// alert ("Dat was "+myFileLocation);


// myFolder = new Folder ([myFileLocation]);
// myFolderContents = myFolder.getFiles("*.doc"); // array
myFolderContents = findAllFiles (myFileLocation);
myFileAmount = myFolderContents.length;

if (myFileAmount < 1)
{
	alert ("Geen .doc bestanden gevonden in de map "+myFileLocation.fsName); // unescape());
	exit(0);
}

/*app.activeDocument.selection[0].parent.insertionPoints[-1].contents = ""+myFileAmount+" bestand(en):\r";

for (i=0; i<myFileAmount; i++)
{
	app.activeDocument.selection[0].parent.insertionPoints[-1].contents = "\r"+myFolderContents[i];
}*/


for (i=0; i<myFolderContents.length; i++)
	myFolderContents[i] = [ myFolderContents[i], myFolderContents[i].fsName ];

while (1)
{
	slash = myFolderContents[0][1].indexOf("\\");
	if (slash == -1)
		slash = myFolderContents[0][1].indexOf("/");
	if (slash == -1)
		break;

	pt = myFolderContents[0][1].substr(0,slash);
	for (i=0; i<myFolderContents.length; i++)
	{
		if (myFolderContents[i][1].substr(0,slash) != pt)
			break;
	}
	if (i<myFolderContents.length)
		break;
	for (i=0; i<myFolderContents.length; i++)
		myFolderContents[i][1] = myFolderContents[i][1].substr(slash+1);
}

myFolderContents.sort ();

for (i=myFolderContents.length-1; i>0; i--)
{
	if (myFolderContents[i][1].match(/\.docx$/) &&
		myFolderContents[i-1][1].match(/\.doc$/) &&
		myFolderContents[i][1].substring(0,myFolderContents[i][1].lastIndexOf('.')) ==
		myFolderContents[i-1][1].substring(0,myFolderContents[i-1][1].lastIndexOf('.')))
	{
		myFileAmount--;
		myFolderContents.splice(i,1);
	}
}

myFolderContents.sort (sortByNumber);

list = [];
for (i=0; i<myFolderContents.length; i++)
	list.push (myFolderContents[i][1]);

if (confirm("Alle "+myFileAmount+" bestanden inlezen?\r"+list.join("\r")) == false)
	exit(0);

app.scriptPreferences.enableRedraw = false;

pg = 0;
target = app.selection[0].parentTextFrames[0];
// alert (target);
app.activeDocument.viewPreferences.rulerOrigin = RulerOrigin.PAGE_ORIGIN;

var failList = [];

for (i=0; i<myFileAmount; i++)
{

	if (i > 0)
		app.activeDocument.selection[0].parent.insertionPoints[-1].contents = "\r\r\r\r";
	app.activeDocument.selection[0].parent.insertionPoints[-1].properties = {pointSize:24, appliedFont:"Times New Roman\tRegular", underline:false, fillColor:app.swatches.item("Black")};
	app.activeDocument.selection[0].parent.insertionPoints[-1].contents = myFolderContents[i][1]+"\r\r";
	
	start = app.activeDocument.selection[0].paragraphs[0];
	
	app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
	try
	{
		app.activeDocument.selection[0].parent.insertionPoints[-1].place (myFolderContents[i][0], false);
	} catch (e)
	{
		app.scriptPreferences.userInteractionLevel = UserInteractionLevels.INTERACT_WITH_ALL;
	//	alert ("Could not import "+myFolderContents[i][1]);
		failList.push (myFolderContents[i][1]);
	}
	app.scriptPreferences.userInteractionLevel = UserInteractionLevels.INTERACT_WITH_ALL;

//	target.parentStory.paragraphs.everyItem().applyParagraphStyle (app.activeDocument.paragraphStyles[0], false);
	target.parentStory.paragraphs.itemByRange(start,target.parentStory.paragraphs.lastItem()).applyParagraphStyle (app.activeDocument.paragraphStyles[0], false);
	target.parentStory.paragraphs.everyItem().applyCharacterStyle (app.activeDocument.characterStyles[0], false);

	j = app.activeDocument.paragraphStyles.length-1;
	do
	{
		if (app.activeDocument.paragraphStyles[j].imported == true)
			app.activeDocument.paragraphStyles[j].remove();
		j--;
	} while (j > 0);

	j = app.activeDocument.characterStyles.length-1;
	do
	{
		if (app.activeDocument.characterStyles[j].imported == true)
			app.activeDocument.characterStyles[j].remove();
		j--;
	} while (j > 0);

/*	graphs = app.activeDocument.allGraphics;
	textwidth = target.geometricBounds;
	textwidth = textwidth[3]-textwidth[1];
	switch (app.activeDocument.viewPreferences.horizontalMeasurementUnits)
	{
		case MeasurementUnits.POINTS: break;
		case MeasurementUnits.PICAS: textwidth*=12; break;
		case MeasurementUnits.INCHES: textwidth*=72; break;
		case MeasurementUnits.INCHES_DECIMAL: textwidth*=72; break;
		case MeasurementUnits.MILLIMETERS: textwidth/=25.4; textwidth*=72; break;
		case MeasurementUnits.CENTIMETERS: textwidth/=2.54; textwidth*=72; break;
		default:
			alert ('ja doeg!');exit(0);
	}

	for (i=0; i<graphs.length; i++)
	{
		w = graphs[i].parent.resolve(AnchorPoint.BOTTOM_RIGHT_ANCHOR, CoordinateSpaces.INNER_COORDINATES);
		if (w[0][0] > textwidth)
		{
			f = textwidth/w[0][0];
			myTransformationMatrix = app.transformationMatrices.add({horizontalScaleFactor:f,verticalScaleFactor:f});
			graphs[i].parent.transform(CoordinateSpaces.INNER_COORDINATES, AnchorPoint.TOP_LEFT_ANCHOR, myTransformationMatrix, MatrixContent.SCALE_VALUES);
		}
	} */


	target = target.endTextFrame;
	while (target.overflows)
	{
		pg = target.parent.documentOffset;
		if (pg == app.activeDocument.pages.length-1)
		{
		//	alert ("add a page");
			app.activeDocument.pages.add();
			pg++;
		}
		if (target.nextTextFrame)
		{
		//	alert ("go to next page "+pg);
			target = target.nextTextFrame;
		}
		else
		{
		//	alert ("add frame on page "+pg);
			target.nextTextFrame = app.activeDocument.pages[pg].textFrames.add();
			target = target.nextTextFrame;
			if (pg & 1)	// Left page
			{
				target.geometricBounds = [ app.activeDocument.pages[pg].marginPreferences.top,
					app.activeDocument.pages[pg].marginPreferences.right,
					app.activeDocument.documentPreferences.pageHeight - app.activeDocument.pages[pg].marginPreferences.bottom,
					app.activeDocument.documentPreferences.pageWidth - app.activeDocument.pages[pg].marginPreferences.left ];
			}
			else	// Right page
			{
				target.geometricBounds = [ app.activeDocument.pages[pg].marginPreferences.top,
					app.activeDocument.pages[pg].marginPreferences.left,
					app.activeDocument.documentPreferences.pageHeight - app.activeDocument.pages[pg].marginPreferences.bottom,
					app.activeDocument.documentPreferences.pageWidth - app.activeDocument.pages[pg].marginPreferences.right ];
			}
		}
		if (target.contents.length == 0)
		{
		//	alert ("gave up because frame was empty on page "+pg);
			break;
		}
	}
} 
app.activeDocument.viewPreferences.rulerOrigin = RulerOrigin.SPREAD_ORIGIN;

app.findGrepPreferences = app.changeGrepPreferences = null;

var symbolToUnicode = {
	'\u0009' : '\u0009',
	'\u00B3' : '\u2265',
	'\u00B4' : '\u00D7',
	'\u00B7' : '\u2022'
};
app.findGrepPreferences.appliedFont = "Symbol";
app.changeGrepPreferences.appliedFont = "Times New Roman";
for (i in symbolToUnicode)
{
	app.findGrepPreferences.findWhat = i;
	app.changeGrepPreferences.changeTo = symbolToUnicode[i];
	target.parentStory.changeGrep();
}

var latin1ToUncode = {
'\u0080' : "\u20AC",	// EURO SIGN
'\u0082' : "\u201A",	// SINGLE LOW-9 QUOTATION MARK
'\u0083' : "\u0192",	// LATIN SMALL LETTER F WITH HOOK
'\u0084' : "\u201E",	// DOUBLE LOW-9 QUOTATION MARK
'\u0085' : "\u2026",	// HORIZONTAL ELLIPSIS
'\u0086' : "\u2020",	// DAGGER
'\u0087' : "\u2021",	// DOUBLE DAGGER
'\u0088' : "\u02C6",	// MODIFIER LETTER CIRCUMFLEX ACCENT
'\u0089' : "\u2030",	// PER MILLE SIGN
'\u008A' : "\u0160",	// LATIN CAPITAL LETTER S WITH CARON
'\u008B' : "\u2039",	// SINGLE LEFT-POINTING ANGLE QUOTATION MARK
'\u008C' : "\u0152",	// LATIN CAPITAL LIGATURE OE
'\u008E' : "\u017D",	// LATIN CAPITAL LETTER Z WITH CARON
'\u0091' : "\u2018",	// LEFT SINGLE QUOTATION MARK
'\u0092' : "\u2019",	// RIGHT SINGLE QUOTATION MARK
'\u0093' : "\u201C",	// LEFT DOUBLE QUOTATION MARK
'\u0094' : "\u201D",	// RIGHT DOUBLE QUOTATION MARK
'\u0095' : "\u2022",	// BULLET
'\u0096' : "\u2013",	// EN DASH
'\u0097' : "\u2014",	// EM DASH
'\u0098' : "\u02DC",	// SMALL TILDE
'\u0099' : "\u2122",	// TRADE MARK SIGN
'\u009A' : "\u0161",	// LATIN SMALL LETTER S WITH CARON
'\u009B' : "\u203A",	// SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
'\u009C' : "\u0153",	// LATIN SMALL LIGATURE OE
'\u009E' : "\u017E",	// LATIN SMALL LETTER Z WITH CARON
'\u009F' : "\u0178"		// LATIN CAPITAL LETTER Y WITH DIAERESIS
};

app.findGrepPreferences = app.changeGrepPreferences = null;
for (i in latin1ToUncode)
{
	app.findGrepPreferences.findWhat = i;
	app.changeGrepPreferences.changeTo = latin1ToUncode[i];
	target.parentStory.changeGrep();
}

app.findGrepPreferences.findWhat = "[\\x{E012}\\x{E015}]";
app.changeGrepPreferences.changeTo = "\\r";
target.parentStory.changeGrep();

/*
if (app.selection.length == 1 && app.selection[0].length >= 1)
{
	str = app.selection[0].contents;
	res = '';
	for (i=0; i<str.length; i++)
	if (latin1ToUncode[str[i]])
		res += latin1ToUncode[str[i]];
	else if (latin1ToUncode[String.fromCharCode(str[i] & 0xff)])
		res += latin1ToUncode[String.fromCharCode(str[i])];
	else if ((str[i] & 0xff00) == 0xf000)
		res += String.fromCharCode(str[i] & 0xff);
	else
		res += str[i];
	app.selection[0].contents = res;
}

app.findGrepPreferences.findWhat = "\\x{0085}";
app.changeGrepPreferences.changeTo = '~e';
target.parentStory.changeGrep();
 */

app.findGrepPreferences = app.changeGrepPreferences = null;
app.findGrepPreferences.findWhat = "(?s)(?<!.)\\s+|\\s+(?!.)";
app.changeGrepPreferences.fontStyle = "Regular";

app.findGrepPreferences.fontStyle = "Bold";
target.parentStory.changeGrep();

app.findGrepPreferences.fontStyle = "Italic";
target.parentStory.changeGrep();

app.findGrepPreferences.fontStyle = "Bold Italic";
target.parentStory.changeGrep();

app.findGrepPreferences.fontStyle = '';
app.changeGrepPreferences.fontStyle = '';
app.findGrepPreferences.position = Position.SUPERSCRIPT;
app.changeGrepPreferences.position = Position.NORMAL;
target.parentStory.changeGrep();

app.findGrepPreferences.position = Position.SUBSCRIPT;
target.parentStory.changeGrep();

app.findGrepPreferences = app.changeGrepPreferences = null;

app.scriptPreferences.enableRedraw = true;

if (failList.length)
{
	alert ("Probleem met deze files:\r"+failList.join("\r"));
}


function findAllFiles (/* folder */startAt)
{
	var returns = [];
	var thisList = [];
	var fromFolder = new Folder ([startAt]);

//	alert ("Looking in "+startAt);

	returns = fromFolder.getFiles(function(a) { return a instanceof File && a.name.substr(0,1) != '.' && a.name.match(/\.(docx?|rtf)/i); } ); // array

	thisList = fromFolder.getFiles(function(a) { return a instanceof Folder && a.name.substr(0,1) != '.' } );
//	alert ("this list is: "+thisList.join("\r"));
	while (thisList.length)
	{
		returns = returns.concat (findAllFiles (thisList[0]));
		thisList.shift();
	}

	return returns;
}

function sortByNumber(a,b)
{
	var aa = a[1].toLowerCase(),bb = b[1].toLowerCase();

	if (aa.match(/\.(docx?|rtf)$/) )
		aa = aa.substr(0, aa.lastIndexOf('.'));
	if (bb.match(/\.(docx?|rtf)$/) )
		bb = bb.substr(0, bb.lastIndexOf('.'));

	do
	{
		while (aa.length > 0 && bb.length > 0 &&
			aa.substr(0,1) == bb.substr(0,1))
		{
			if (aa.match(/^[0-9]/) > 0 &&
				bb.match(/^[0-9]/) > 0)
				break;
			aa = aa.substr(1);
			bb = bb.substr(1);
		}
		if (aa.length && !bb.length) return 1;
		if (!aa.length && bb.length) return -1;

		if (!aa.match(/^[0-9]/) ||
			!bb.match(/^[0-9]/))
			break;

		var aaa = Number(aa.match(/^[0-9]+/)[0]);
		var bbb = Number(bb.match(/^[0-9]+/)[0]);
		if (aaa != bbb)
			return aaa > bbb;

		aa = aa.replace(/^[0-9]+/, '');
		bb = bb.replace(/^[0-9]+/, '');
	} while (aa.length && bb.length);
//	alert (aa+" <> "+bb);

	if (aa.length && !bb.length) return 1;
	if (!aa.length && bb.length) return -1;

	var aa = a[1].toLowerCase(),bb = b[1].toLowerCase();
	
//	geen nummers? naam dan?

	var i, order_by_name = [
		"voorw", "titelp", "content", "inhoud",
		"manuscript", "text", "tekst", "running", "korte", "figure", "figuur", "tabel", "table"
	];

	var aaa = 0;
	var bbb = 0;

	for (i=0; i<order_by_name.length; i++)
	{
		if (aa.indexOf(order_by_name[i]) >= 0) aaa += (1<<i);
		if (bb.indexOf(order_by_name[i]) >= 0) bbb += (1<<i);
	}

//	alert (aa+'->'+aaa+'\r'+bb+'->'+bbb);

	if (aaa != bbb) return aaa > bbb;

	return a[1].toLowerCase() > b[1].toLowerCase();
}
This topic has been closed for replies.

1 reply

brian_p_dts
Community Expert
Community Expert
October 12, 2022

If the text frame is on the pasteboard, then target.parent will be null and won't have a document offset to give you. You could check if target.parent.isValid and do something else if not.