script rename and relink
In a corporate context, my images often include special characters that are not tolerated by the platform I'm working on.
I currently have a script that renames images to : "1", "2", "3" etc etc depending on the number of images in the folder.
And that is supposed to automatically relink them with the new name.
However, this doesn't seem to work for an image whose name is: LOGO_ECODESIGN_1 (1) (2)
The script does rename the image in the folder, but is unable to redo the link, whereas it works perfectly for the other 2 images. Here's the code and the link to my indesign document:
Indesign document in my Google Drive
var dossier = Folder.selectDialog("Select a folder with linked images");
if (!dossier.exists) {
alert("Le dossier spécifié n'existe pas.");
exit();
}
var fichiers = dossier.getFiles();
var correspondanceNoms = {};
// Function to sanitize and decode a file name
function sanitizeAndDecodeFileName(fileName) {
var sanitizedFileName = fileName.replace(/[\(\)\s]/g, '_').replace(/[^\w._-]/g, '');
return decodeURIComponent(sanitizedFileName);
}
// Rename files and build correspondanceNoms dictionary
for (var i = 0; i < fichiers.length; i++) {
if (fichiers[i] instanceof File) {
var ancienNom = decodeURI(fichiers[i].name);
var nomNettoye = sanitizeAndDecodeFileName(ancienNom);
var nouveauNom = (i + 1) + nomNettoye.replace(/.*(\..+)$/, "$1");
correspondanceNoms[nomNettoye] = nouveauNom;
fichiers[i].rename(nouveauNom);
}
}
var links = app.activeDocument.links;
// Loop through each link in the document
for (var i = 0; i < links.length; i++) {
var missingFileName = decodeURI(links[i].name);
var missingFileNameClean = sanitizeAndDecodeFileName(missingFileName);
if (correspondanceNoms.hasOwnProperty(missingFileNameClean)) {
var newFileName = correspondanceNoms[missingFileNameClean];
var file = new File(dossier + "/" + newFileName);
if (file.exists) {
try {
links[i].relink(file);
} catch (e) {
alert("Error relinking file: " + file.fsName + "\nError: " + e.message);
}
}
}
}
