Copy link to clipboard
Copied
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);
}
}
}
}
Have you tried Kasyan Servetsky's script that does something similar?
http://kasyan.ho.ua/indesign/link/batch_rename_and_relink.html
Copy link to clipboard
Copied
Have you tried Kasyan Servetsky's script that does something similar?
http://kasyan.ho.ua/indesign/link/batch_rename_and_relink.html
Copy link to clipboard
Copied
Thanks a lot, this is exactly what I needed !
I've adapted this script, which worked perfectly on most of my documents, just removing the dialogue box because I don't need to have a prefix, just simply rename images.
However, I have one case that is not handled by this script (even before I adapted it),
The platform I'm using removes certain special characters directly from image names, such as ®, ©, TM.
As a result, the image name looks like this: _49A7164Jacques Mezger-sRGB
And Indesign shows me a missing link because it has the name: _49A7164©Jacques Mezger-sRGB
The script doesn't rename the image in question and therefore doesn't redo the link, my function
Do you have a solution for this ?
Below the code i'm using for the script if it can help
var myPrefix, myISBN;
var myDoc = app.activeDocument;
var myMultipleLinks = new Array();
var myLinksCounter = 0;
var myScriptName = "Batch rename and relink";
var myProcessedLinkNames = [];
Main();
ClearStructure();
Save();
//------------------------------------------- FUNCTIONS ------------------------------------------------
function Main() {
ClearLabels();
var myPrBarWin = new Window("window", myScriptName);
var myPrBar = myPrBarWin.add("progressbar", [12, 12, 375, 24]);
var myPrBarText = myPrBarWin.add("statictext", undefined, "Starting");
myPrBarText.bounds = [0, 0, 365, 20];
myPrBarText.alignment = "left";
var myPages = myDoc.pages;
myPrBar.minvalue = 0;
myPrBar.maxvalue = myPages.length;
var imageCounter = 1; // Compteur pour le nommage des images
for (var p = 0; p < myPages.length; p++) {
var myLinks = myPages[p].allGraphics;
myPrBarWin.show();
for (var k = myLinks.length - 1; k >= 0; k--) {
try {
var myLink = myLinks[k].itemLink;
if (myLink.extractLabel("relinked") != "yes") {
var myOldLinkName = sanitizeFileName(myLink.name);
var myExtension = myOldLinkName.substr(myOldLinkName.lastIndexOf("."));
if (LinkUsage(myLink) == 1) {
var myNewLinkName = imageCounter + myExtension; // Nouveau nom basé uniquement sur le compteur
myPrBar.value = (p + 1);
myPrBarText.text = "Renaming " + myOldLinkName + " on page " + myPages[p].name;
var myOldImageHDfile = new File(myLink.filePath);
var myRenameResult = myOldImageHDfile.rename(myNewLinkName);
if (myRenameResult) {
myLink.insertLabel("relinked", "yes");
myLink.relink(myOldImageHDfile);
try {
myLink = myLink.update();
} catch(err) {}
myLinksCounter++;
imageCounter++; // Incrémenter le compteur d'images
}
} else {
ProcessMultiUsedLinks(myLink);
}
}
} catch(err) {
$.writeln(err.message + ", line: " + err.line);
}
}
}
myPrBarWin.close();
}
function sanitizeFileName(fileName) {
return fileName.replace(/®/g, 'R')
.replace(/©/g, 'C')
.replace(/™/g, 'TM')
// Ajoutez d'autres remplacements si nécessaire
}
// Check how many times the link was placed
function LinkUsage(myLink) {
var myLinksNumber = 0;
for (var c = 0; c < myDoc.links.length; c++) {
if (myLink.filePath == myDoc.links[c].filePath) {
myLinksNumber += 1;
}
}
return myLinksNumber;
}
//--------------------------------------------------------------------------------------------------------------
// Relink the links placed more than once
function ProcessMultiUsedLinks(myLink) {
if (IsObjInArray(myLink, myProcessedLinkNames)) return;
var myExtension = myLink.name.substr(myLink.name.lastIndexOf("."));
var myMultiUsedLink = new Array();
var myAllLinks = myDoc.links;
for (var d = 0; d < myAllLinks.length; d++) {
if (myAllLinks[d].filePath == myLink.filePath) {
myMultiUsedLink.push(myAllLinks[d]);
}
}
try {
myLink.show();
}
catch(err) {}
var myNewLinkName = prompt("Enter a name for this image", GetFileNameOnly(myLink.name), "This image is placed " + myMultiUsedLink.length + " times");
if (myNewLinkName) {
if (myNewLinkName + myExtension != myLink.name) {
var myOldImageHDfile = new File(myLink.filePath);
var myRenameResult = myOldImageHDfile.rename(myNewLinkName + myExtension);
if (myRenameResult) {
myLink.insertLabel("relinked", "yes");
myLink.relink(myOldImageHDfile);
try {
myLink = myLink.update();
}
catch(err) {}
myLinksCounter++;
for (var f = myMultiUsedLink.length-1; f >= 0; f--) {
var myCurrLink = myMultiUsedLink[f];
if (myNewLinkName + myExtension != myCurrLink.name) {
myCurrLink.insertLabel("relinked", "yes");
myCurrLink.relink(myOldImageHDfile);
myLinksCounter++;
try {
myCurrLink = myLink.update();
}
catch(err) {}
}
}
}
}
}
else {
myProcessedLinkNames.push(myLink);
}
UpdateAllOutdatedLinks();
}
//--------------------------------------------------------------------------------------------------------------
// Clear labels in case this script has been already run on the current document
function ClearLabels() {
for (var f = 0; f < myDoc.links.length; f++) {
if (myDoc.links[f].extractLabel("relinked") != "") {
myDoc.links[f].insertLabel("relinked", "");
}
}
}
//--------------------------------------------------------------------------------------------------------------
function UpdateAllOutdatedLinks() {
for(var myCounter = myDoc.links.length-1; myCounter >= 0; myCounter--){
var myLink = myDoc.links[myCounter];
if (myLink.status == LinkStatus.linkOutOfDate){
myLink.update();
}
}
}
//--------------------------------------------------------------------------------------------------------------
function Pad0000(myNumber) {
return ("0000" + myNumber).match (/....$/)[0];
}
//--------------------------------------------------------------------------------------------------------------
function GetFileNameOnly(myFileName) {
var myString = "";
var myResult = myFileName.lastIndexOf(".");
if (myResult == -1) {
myString = myFileName;
}
else {
myString = myFileName.substr(0, myResult);
}
return myString;
}
//--------------------------------------------------------------------------------------------------------------
function IsObjInArray(myObj, myArray) {
for (x in myArray) {
if (myObj.filePath == myArray[x].filePath) {
return true;
}
}
return false;
}
//--------------------------------------------------------------------------------------------------------------
function ClearStructure() {
// Get the active InDesign document
var doc = app.activeDocument;
// Check if the document has XML structure
if (doc.xmlElements.length === 0) {
alert("No XML structure found in the document.");
return;
}
// Get the root XML element of the document
var root = doc.xmlElements[0];
// Get the child elements (tags) of the root element
var tags = root.xmlElements;
// Get the attributes of the root element
var attr = root.xmlAttributes;
// Loop through each child element (tag) in reverse order and untag it
for (var i = tags.length - 1; i >= 0; i--) {
// Untag the current child element
tags[i].untag();
}
// Loop through each attribute in reverse order and remove it
for (var i = attr.length - 1; i >= 0; i--) {
// Remove the current attribute
attr[i].remove();
}
// Remove the root element
root.remove();
}
function Save() {
var doc = app.activeDocument; // Récupérer le document InDesign actif
doc.save(); // Save
}
Copy link to clipboard
Copied
I had a similar situation with space reeading as %20, what i did was to use regex to repalce it in the filename, in your case you would replace those chars with nothing (delete it) in sanitizeFileName ()