Illustrator — пакетная вставка имени файла в сценарий textpath приводит к сбою Illustrator

Во-первых: я не программист. Просто играю с кодом и пытаюсь заставить его работать для конкретной задачи:

Вот скрипт, который я сделал для вставки текста с именем файла в более чем 600 файлов PDF. Предполагается, что это будет работать со всеми файлами в выбранной папке.

Проблема: Illustrator падает.

Первый тестовый код, после нескольких отредактированных файлов Illustrator завис, поэтому я попытался ввести задержку после каждого сохранения, чтобы замедлить пакетный процесс.

$.setTimeout(функция () {sourceDoc.close(SaveOptions.SAVECHANGES)}, 1000);

Не знаю, что делать дальше. Код работает, если я удалю эту строку: sourceDoc.close(SaveOptions.SAVECHANGES);

Here is the complete script:

    var destFolder, sourceFolder, files, fileType, sourceDoc, layers, writeText, finLabel;  
      
    // Select the source folder.  
    sourceFolder = Folder.selectDialog( 'Select the folder with Illustrator files you want to convert to PNG', '~' );  
      
    // If a valid folder is selected  
    if ( sourceFolder != null )  
    {  
    files = new Array();  
    fileType = prompt( 'Select type of Illustrator files to you want to process. Eg: *.ai', '*.pdf' );  
      
    // Get all files matching the pattern  
    files = sourceFolder.getFiles( fileType );  
      
    if ( files.length > 0 )  
    for ( i = 0; i < files.length; i++ )  
    {  
        sourceDoc = app.open(files[i]); // returns the document object  
        layers = unlock();  
        writeText = getFilename();  
        finLabel = remText();  
        sourceDoc.close(SaveOptions.SAVECHANGES);   //if save command line is deleted the code works   WTF???  
        $.setTimeout(function () {sourceDoc.close(SaveOptions.SAVECHANGES)}, 1000); // still crashes using delay ...  
    }  
    //alert( 'Files are saved as PNG in ' + destFolder );  
      
    else  
    {  
    alert( 'No matching files found' );  
    }  
    }  
      
    function unlock()  
    {  
       //get the total number of layers in the active document  
    doc = app.activeDocument;  
    var totalLayers = doc.layers.length;  
      
    //looping on layers to create one artboard per layer  
    for ( var i = 0 ; i < totalLayers ; i++){  
          
        var currentLayer = doc.layers[i];  
          
        //We don't want to deal with hidden layers  
        if(currentLayer.visible == false) continue;  
          
        //Unlock the layer if needed  
        currentLayer.locked = false;  
      
    }  
        }  
      
    function getFilename()  
    {  
    // Write text  
    var pointTextRef = app.activeDocument.textFrames.add();  
    pointTextRef.contents = app.activeDocument.name + "\n" + "YBS";  
    pointTextRef.top = 0;  
    pointTextRef.left = 0;  
    app.activeDocument.textFrames[0].textRange.characterAttributes.textFont=app.textFonts[31];  
          
        }  
      
    function remText()  
    {  
    // This works for search and replace :))))))  
      
        var active_doc = app.activeDocument;    
            
        var search_string = /_Template.pdf/gi; // g for global search, remove i to make a case sensitive search    
        var replace_string = '';    
            
        var text_frames = active_doc.textFrames;    
            
        if (text_frames.length > 0)    
        {    
            for (var i = 0 ; i < text_frames.length; i++)    
              {    
                  var this_text_frame = text_frames[i];    
                   var new_string = this_text_frame.contents.replace(search_string, replace_string);    
                       
                   if (new_string != this_text_frame.contents)    
                       {    
                            this_text_frame.contents = new_string;    
                       }    
              }    
        }        
     }  

Любые идеи о том, что вызывает сбой Illustrator?

Примечание. Приложение аварийно завершает работу после открытия первого файла.

Спасибо за помощь!


person Liviu Iancu    schedule 28.09.2014    source источник


Ответы (2)


Некоторые вещи, которые вы должны изменить и попробовать:

  1. В расширении нет $.setTimeout
  2. Проверьте, действительно ли работает ваш файловый фильтр (getFiles(FileType))
  3. Ваши функции unlock(), getFilename() и remText() не имеют возвращаемого значения, поэтому вам не нужно передавать их результат в переменную.
  4. Попробуйте подмножество ваших файлов PDF, а не все 600
  5. добавьте var в цикл for for(var i = 0; i < ...)
  6. Попробуйте сделать свой for цикл с конца списка файлов for (var i = files.length; i >= 0; i-- ){}
person fabianmoronzirfas    schedule 29.09.2014

После удаления этой строки:

 $.setTimeout(function () {sourceDoc.close(SaveOptions.SAVECHANGES)}, 1000); 

код работал на 499 файлах за один пакет :)

Оказывается, Illustrator аварийно завершает работу при попытке сохранить поврежденный PDF-файл.

@fabianteblind Спасибо за помощь!

person Liviu Iancu    schedule 29.09.2014