How to fill document title metadata with file name via script
Took me a while to piece working code together for an Illustrator script (jsx) that can be run from the Illustrator scripts menu, wish there was better documentation. Sharing with everyone else...
try {
var docRef = app.activeDocument;
var docPath = docRef.path.fsName;
var docName = docRef.name.replace(/(.*?)(?:\.([^.]+))?$/,'$1');
var docExtension = docRef.name.replace(/(.*?)(?:(\.[^.]+))?$/,'$2');
docRef = setDocumentTitleMetadata(docRef, docName);
//do other stuff
}
catch(e) {
alert('error:' + e.message);
}
function setDocumentTitleMetadata(docRef, title) {
// load xmp library required
loadXMPLibrary();
// get full document path + name
var fullPath = docRef.path.fsName + getPathSeparator(docRef.path.fsName) + docRef.name;
// open xmp
var xmpFile = new XMPFile(fullPath, XMPConst.UNKNOWN, XMPConst.OPEN_FOR_UPDATE);
// open xmp metadata
var xmp = xmpFile.getXMP();
// unset old title
xmp.deleteProperty(XMPConst.NS_DC, "title");
// set new title
xmp.setLocalizedText(XMPConst.NS_DC, "title", null, "x-default", title);
// update xmp with new metadata
xmpFile.putXMP(xmp);
// close xmp
xmpFile.closeFile(XMPConst.CLOSE_UPDATE_SAFELY);
// unload xmp library no longer required
unloadXMPLibrary();
// skipping this step will overwrite your changes if you save the active document
closeAndOpenDocument(docRef, fullPath);
// return the newly opened document
return app.activeDocument;
}
function loadXMPLibrary() {
if (!ExternalObject.AdobeXMPScript) {
try {
ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');
}
catch (e) {
alert('Unable to load the AdobeXMPScript library!');
return false;
}
}
return true;
}
function unloadXMPLibrary() {
if(ExternalObject.AdobeXMPScript) {
try {
ExternalObject.AdobeXMPScript.unload();
ExternalObject.AdobeXMPScript = undefined;
} catch (e) {
alert('Unable to unload the AdobeXMPScript library!');
return false;
}
}
return true;
}
function closeAndOpenDocument(docRef, fullPath) {
app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
docRef.close(SaveOptions.DONOTSAVECHANGES);
app.open(new File(fullPath));
app.userInteractionLevel = UserInteractionLevel.DISPLAYALERTS;
}
function getPathSeparator(fullPath) {
if(fullPath.indexOf("\\") > -1) {
return "\\";
}
return "/";
}The script above updates the active document's title to the file name without the extension and then closes and re-opens the active document. If you do not close and re-open the document saving will revert the document title to whatever is currently in the box in the user interface of Illustrator. The document title and file name will get out of sync when changing the file name outside of Illustrator.
Enjoy.