Skip to main content
Known Participant
February 24, 2023
Answered

Résolution d'un script javascript

  • February 24, 2023
  • 1 reply
  • 904 views

Bonjour à tous, je souhaiter créer un script capable d'exporter mon fichier .ai en jpg puis de convertir le jpg en PDF ce que j'ai réussi à faire malheuresement j'ai voulu rajouter une option pour exporter tous les fichiers ouverts dans illustrator et je ne trouve pas la bonne solution. A l'heure acutelle quand je souhaite exporter tous les fichiers ouverts sur illustrator le script m'exporte uniquement mon fichier actif en autant de copies qu'il n'y a de fichiers ouverts sur illustrator au lieu de m'exporter chaque fichier.
Voici mon script

// Vérifie si un document est ouvert
if (app.documents.length == 0) {
  alert("Aucun document ouvert.");
} else {
// Crée une fenêtre avec une question et deux boutons cliquables
var exportAllDocs = false;
var exportDocDlg = new Window("dialog", "SAI - PDF EXPORT", undefined);
exportDocDlg.add("statictext", undefined, "Sélectionner l'option d'export souhaitée:");
var btnGroup = exportDocDlg.add("group");

var docBtn = btnGroup.add("button", undefined, "Document actif seulement");
docBtn.onClick = function() {
    exportAllDocs = false;
    exportDocDlg.close();
};
var allDocsBtn = btnGroup.add("button", undefined, "Tous les documents ouverts");
allDocsBtn.onClick = function() {
    exportAllDocs = true;
    exportDocDlg.close();
};
exportDocDlg.show();


// Si l'utilisateur a choisi d'exporter tous les documents ouverts, traite-les tous
var documents;
if (exportAllDocs) {
  documents = app.documents;
  for (var i = 0; i < documents.length; i++) {
    var currentDocument = documents[i];
    var nonPrintableLayer = currentDocument.layers.getByName("NON IMPRIMABLE");
    if (nonPrintableLayer) {
      // Désactive le calque "NON IMPRIMABLE"
      nonPrintableLayer.visible = false;
    }
  }
}
// Sinon, exporte uniquement le document actif
else {
  // Exporte uniquement le document actif
  documents = [app.activeDocument];
  for (var i = 0; i < documents.length; i++) {
    var currentDocument = documents[i];
    var nonPrintableLayer = currentDocument.layers.getByName("NON IMPRIMABLE");
    if (nonPrintableLayer) {
    // Désactive le calque "NON IMPRIMABLE"
    nonPrintableLayer.visible = false;
}
  }
}

// Parcourt tous les fichiers à exporter
for (var i = 0; i < documents.length; i++) {
  var currentDocument = documents[i];
 
  // Récupère le nom du document
  var docName = currentDocument.name;

  // Récupère le chemin d'accès du document
  var docPath = currentDocument.path;

  // Définit le nom du fichier PDF en ajoutant l'extension .pdf
  var pdfName = docName.replace(/\.[^\.]+$/, '') + ".pdf";


    // Exporte le plan de travail au format JPG sans le calque "NON IMPRIMABLE"
    var jpgExportOpts = new ExportOptionsJPEG();
    jpgExportOpts.artBoardClipping = true;
    jpgExportOpts.horizontalScale = 200; // 20 fois supérieure à la résolution de base
    jpgExportOpts.verticalScale = 200; // 20 fois supérieure à la résolution de base
    jpgExportOpts.qualitySetting = 100;
    var jpgFile = new File(docPath + "/" + docName.replace(/\.[^\.]+$/, '') + ".jpg");
    currentDocument.exportFile(jpgFile, ExportType.JPEG, jpgExportOpts);


    // Réactive le calque "NON IMPRIMABLE"
    if (nonPrintableLayer) {
      nonPrintableLayer.visible = true;
    }

 // Ouvre le fichier JPG pour obtenir les limites de l'illustration
 var jpgDoc = app.open(jpgFile);
 var jpgLayer = jpgDoc.layers[0];
 var jpgBounds = jpgDoc.visibleBounds;

 // Ajuste les limites du plan de travail pour qu'elles correspondent aux limites de l'illustration
 var activeArtboard = currentDocument.artboards[currentDocument.artboards.getActiveArtboardIndex()];
 activeArtboard.artboardRect = jpgBounds;

  // Ouvre le fichier JPG et le convertit en PDF
  var pdfExportOpts = new PDFSaveOptions();
  var pdfFile = new File(docPath + "/" + pdfName);
  jpgDoc.saveAs(pdfFile, pdfExportOpts);
  pdfExportOpts.horizontalScale = 0.1; // 20 fois supérieure à la résolution de base
  pdfExportOpts.verticalScale = 0.1; // 20 fois supérieure à la résolution de base

  // Ferme le fichier JPG et supprime le fichier JPG original
  jpgDoc.close(SaveOptions.DONOTSAVECHANGES);
  jpgFile.remove();

}
// afficher un message de confirmation
alert("L'export PDF a été réalisé avec succès !");

}
This topic has been closed for replies.
Correct answer m1b

Hi @polotrobo, I've modified your script a bit. It would be good learning for you to go through it carefully to understand what I changed. Is it your intention is to make a low-resolution, raster image of the document as a pdf? Because if you just wanted a pdf you could have just done saveAs without exporting the temporary jpg file. Anyway, I think I've fixed the structural issue you had (and a bunch of other things I hope).

- Mark

 

 

 

(function () {


    // Check if a document is open
    if (app.documents.length == 0) {
        alert("No open document.");
        return
    }

    // Create a window with a question and two clickable buttons
    var exportAllDocs = false;
    var exportDocDlg = new Window("dialog", "SAI-PDF EXPORT", undefined);
    exportDocDlg.add("statictext", undefined, "Select the desired export option:");
    var btnGroup = exportDocDlg.add("group");

    var docBtn = btnGroup.add("button", undefined, "Active document only", { name: 'ok' });
    docBtn.onClick = function () { exportDocDlg.close(1); };
    var allDocsBtn = btnGroup.add("button", undefined, "All open documents");
    allDocsBtn.onClick = function () { exportDocDlg.close(3) };
    var result = exportDocDlg.show();

    if (result == 2)
        // user cancelled
        return;

    // If the user chose to export all open documents, process them all
    var docs = result == 1 ? [app.activeDocument] : app.documents,
        docCount = docs.length;

    var jpgExportOpts = new ExportOptionsJPEG();
    jpgExportOpts.artBoardClipping = true;
    jpgExportOpts.horizontalScale = 200; // 20 times higher than base resolution
    jpgExportOpts.verticalScale = 200; // 20 times higher than base resolution
    jpgExportOpts.qualitySetting = 100;

    for (var i = 0; i < docCount; i++) {

        var currentDocument = docs[i],
            docName = currentDocument.name,
            docPath = currentDocument.path,
            pdfName = docName.replace(/\.[^\.]+$/, ".pdf"),
            jpgName = docName.replace(/\.[^\.]+$/, ".jpg").replace(' ', '-');

        app.activeDocument = currentDocument;

        // Disable the "NON PRINTABLE" layer
        var nonPrintableLayer;
        try {
            nonPrintableLayer = currentDocument.layers.getByName("NOT PRINTABLE");
            nonPrintableLayer.visible = false;
        } catch (error) { }

        var jpgFile = new File(docPath + "/" + jpgName);
        currentDocument.exportFile(jpgFile, ExportType.JPEG, jpgExportOpts);

        // Reactivate the "NON PRINTABLE" layer
        if (nonPrintableLayer) {
            nonPrintableLayer.visible = true;
        }

        // Open the JPG file to get the boundaries of the illustration
        var jpgDoc = app.open(jpgFile),
            jpgBounds = jpgDoc.rasterItems[0].geometricBounds;

        // Adjust the artboard boundaries to match the artwork boundaries
        currentDocument.artboards[0].artboardRect = jpgBounds;

        // Open the JPG file and convert it to PDF
        var pdfExportOpts = new PDFSaveOptions();
        var pdfFile = new File(docPath + "/" + pdfName);
        jpgDoc.saveAs(pdfFile, pdfExportOpts);

        // Close the JPG file and delete the original JPG file
        jpgDoc.close(SaveOptions.DONOTSAVECHANGES);
        jpgFile.remove();

    }

    // display a confirmation message
    alert("PDF export completed successfully!");

})();

 

 

1 reply

m1b
Community Expert
m1bCommunity ExpertCorrect answer
Community Expert
February 25, 2023

Hi @polotrobo, I've modified your script a bit. It would be good learning for you to go through it carefully to understand what I changed. Is it your intention is to make a low-resolution, raster image of the document as a pdf? Because if you just wanted a pdf you could have just done saveAs without exporting the temporary jpg file. Anyway, I think I've fixed the structural issue you had (and a bunch of other things I hope).

- Mark

 

 

 

(function () {


    // Check if a document is open
    if (app.documents.length == 0) {
        alert("No open document.");
        return
    }

    // Create a window with a question and two clickable buttons
    var exportAllDocs = false;
    var exportDocDlg = new Window("dialog", "SAI-PDF EXPORT", undefined);
    exportDocDlg.add("statictext", undefined, "Select the desired export option:");
    var btnGroup = exportDocDlg.add("group");

    var docBtn = btnGroup.add("button", undefined, "Active document only", { name: 'ok' });
    docBtn.onClick = function () { exportDocDlg.close(1); };
    var allDocsBtn = btnGroup.add("button", undefined, "All open documents");
    allDocsBtn.onClick = function () { exportDocDlg.close(3) };
    var result = exportDocDlg.show();

    if (result == 2)
        // user cancelled
        return;

    // If the user chose to export all open documents, process them all
    var docs = result == 1 ? [app.activeDocument] : app.documents,
        docCount = docs.length;

    var jpgExportOpts = new ExportOptionsJPEG();
    jpgExportOpts.artBoardClipping = true;
    jpgExportOpts.horizontalScale = 200; // 20 times higher than base resolution
    jpgExportOpts.verticalScale = 200; // 20 times higher than base resolution
    jpgExportOpts.qualitySetting = 100;

    for (var i = 0; i < docCount; i++) {

        var currentDocument = docs[i],
            docName = currentDocument.name,
            docPath = currentDocument.path,
            pdfName = docName.replace(/\.[^\.]+$/, ".pdf"),
            jpgName = docName.replace(/\.[^\.]+$/, ".jpg").replace(' ', '-');

        app.activeDocument = currentDocument;

        // Disable the "NON PRINTABLE" layer
        var nonPrintableLayer;
        try {
            nonPrintableLayer = currentDocument.layers.getByName("NOT PRINTABLE");
            nonPrintableLayer.visible = false;
        } catch (error) { }

        var jpgFile = new File(docPath + "/" + jpgName);
        currentDocument.exportFile(jpgFile, ExportType.JPEG, jpgExportOpts);

        // Reactivate the "NON PRINTABLE" layer
        if (nonPrintableLayer) {
            nonPrintableLayer.visible = true;
        }

        // Open the JPG file to get the boundaries of the illustration
        var jpgDoc = app.open(jpgFile),
            jpgBounds = jpgDoc.rasterItems[0].geometricBounds;

        // Adjust the artboard boundaries to match the artwork boundaries
        currentDocument.artboards[0].artboardRect = jpgBounds;

        // Open the JPG file and convert it to PDF
        var pdfExportOpts = new PDFSaveOptions();
        var pdfFile = new File(docPath + "/" + pdfName);
        jpgDoc.saveAs(pdfFile, pdfExportOpts);

        // Close the JPG file and delete the original JPG file
        jpgDoc.close(SaveOptions.DONOTSAVECHANGES);
        jpgFile.remove();

    }

    // display a confirmation message
    alert("PDF export completed successfully!");

})();

 

 

polotroboAuthor
Known Participant
February 27, 2023

Bonjour @m1b
Merci beaucoup pour votre aide votre script est absolument parfait !! Bonne continuation à vous 🙂

PM

m1b
Community Expert
Community Expert
February 27, 2023

You're welcome! 🙂