Quantcast
Channel: Adobe Community : Unanswered Discussions - General and cross-application scripting
Viewing all articles
Browse latest Browse all 84

Adobe Illustrator CS6 vs CC / svg / ExtendScript

$
0
0

Hello,

 

Our customer uses Adobe Illustrator to create illustrations in svg format in order to integrate them into training documents.
Two ExtendScript scripts in Illustrator CS6 allows to convert these svg files.
Since the Illustrator CC migration, these scripts behave differently and do not produce the expected result ... the resulting csv is zero (0KB).
We are looking for an ExtendScript / SVG / Illustrator expert to help us adapting these scripts to work with Illustrator CC.

 

The input svg file is here: https://www.partage-fichiers.com/upload/mhg9ngae/

 

 

Step1 - script 1:

if(documents.length > 0)
{    //Retrieve document path    var docPath = documents[0].path;       //Init log path    var logPath = docPath + "/logs.txt";        //delete old log file    var logFile= new File(logPath);    /*if(logFile.exists)    {
try
{
logFile.remove ();
}
catch(exc)
{
$.writeln("Impossible to delete old log file.");
$.writeln(exc);
}    }*/     WriteLog("Begin CreateSvgSource");         //WriteLog("Document path: " + docPath);    var docName = documents[0].name;    //WriteLog("Document name: " + docName);    var currentdocPath = docPath + "/" +docName;    WriteLog("Current doc path: " + currentdocPath);       var currentDoc = documents[0];    //Construct mapping xml path    var mappingXmlPath = docPath + "/smgMapping.xml";    //WriteLog("Mapping file path: " + mappingXmlPath);    //Test if mapping xml file exist    mappingXmlFile = new File(mappingXmlPath);    if (!mappingXmlFile.exists)    {        WriteLog("No Mapping file to manage.");        // Save as svg and close current doc.        SaveToSvg(currentDoc);    }    else    {        //Open and read content of the mapping xml file        mappingXmlFile.open ("r");        var xmlStr = mappingXmlFile.read();        mappingXmlFile.close();        var root = new XML(xmlStr);        //WriteLog("xml details: " + root.toString ());        var componentList = root.xpath("/smgBankKeys/property");        var componentsLength = componentList.length();               for (var c = 0; c < componentsLength; c++) {            var aiIDvalue = componentList[c].@aiID;            //WriteLog("Legacy text brut value: " + aiIDvalue);            var aiIDcorrected = aiIDvalue.toString().replace (/_/g, ' ');            var legacyTextResult = getLegacyTextFromDocument(currentDoc,aiIDcorrected);            if(legacyTextResult==null)            {                WriteLog("Legacy text not found for : " + aiIDcorrected + " *** original value from behavior=> " + aiIDvalue);            }            else            {                if(legacyTextResult.name=="")                    WriteLog(aiIDcorrected + " not  used directly");                else                    WriteLog("Legacy text found for (from result) : " + legacyTextResult.name);                //WriteLog("Type=> " + legacyTextResult.typename);                //Set element id in svg document                if(aiIDcorrected==legacyTextResult.name)                    componentList[c].@svgID = aiIDvalue+"_1_";                else                    componentList[c].@svgID = aiIDvalue;                try                  {                    //Test if convertToNative method is available before to apply it                    if(legacyTextResult.convertToNative)                    {                        var tmpGroupItem = legacyTextResult.convertToNative(); //Legacy text have been transform in text frame                    }                    else                    {                        WriteLog("ConvertToNative not applicable for: "+aiIDcorrected);                    }                  }                catch(err)                  {                      WriteLog("Impossible to convert element =>"+aiIDcorrected);                      WriteLog(err);                      componentList[c].@svgID = "";//reset modification                      continue; //skip this element                  }            }        }                  //Open and edit content of the mapping xml file        mappingXmlFile.open ("w");        mappingXmlFile.write (root.toString())        mappingXmlFile.close();               // Save as svg and close current doc.        SaveToSvg(currentDoc);    }    WriteLog("End CreateSvgSource");
}
else
{   alert("No document is currently available.");
}


/*********************************************************


Functions definition


**********************************************************/


function SaveToSvg(currentDoc)
{
        // Save as svg and close current doc.        var targetFile = getNewName();        var svgSaveOpts = getSVGOptions();        currentDoc.exportFile(targetFile, ExportType.SVG, svgSaveOpts);        //var currentdocFile = new File("C:\\SMG5\\Sources\\Tool\\bankLite\\LF21_SECAMPR101\\LF21_SECAMPR101_test.ai");        //documents[0].saveAs(currentdocFile,SaveOptions.SAVECHANGES);        currentDoc.close(SaveOptions.DONOTSAVECHANGES);
 }


function getNewName()
{
var ext, docName, newName, saveInFile, docName;
docName = documents[0].name;
    /*121113 RMA correction name management for converted file    var nameSplitted = docName.split(" [Converti]");*/    var searchConvertStartValue = "[";    var searchConvertEndValue = "]";       var convertTagStartIndex = docName.lastIndexOf (searchConvertStartValue);    var convertTagEndIndex = docName.lastIndexOf (searchConvertEndValue);   
ext = '.src.svg'; // new extension for svg file
newName = "";   // if(nameSplitted.length>1)    if(convertTagStartIndex>0 && convertTagEndIndex>0 && (convertTagStartIndex<convertTagEndIndex))    {        newName += docName.substring (0, convertTagStartIndex);        //Remove space at name end        var spaceIndexToTest = newName.length-1;        if(newName.charAt (spaceIndexToTest) == " ")        {             newName=docName.substring (0, spaceIndexToTest);        }        //newName += nameSplitted[0];     }    else    {        var searchValue = ".ai";        var index = docName.search (searchValue);        newName += docName.substr (0, index);           }
newName += ext; // full svg name of the file

// Create a file object to save the svg
saveInFile = new File( documents[0].path + '/' + newName );


return saveInFile;
}


//Build defaut option for svg  saving
function getSVGOptions()
{
var svgSaveOpts = new ExportOptionsSVG();    //just using defaults aside from what's written below    //see http://cssdk.host.adobe.com/sdk/1.0/docs/WebHelp/references/csawlib/com/adobe/illustrator/ExportOptionsSVG.html    svgSaveOpts.embedRasterImages = true;    svgSaveOpts.documentEncoding = SVGDocumentEncoding.UTF8;    svgSaveOpts.DTD = SVGDTDVersion.SVG1_1;    svgSaveOpts.preserveEditability = true;    svgSaveOpts.includeFileInfo     = true; //to include metadata and title

return svgSaveOpts;
}


function getLegacyTextFromDocument(iDoc,LegacyTextID)
{
    var result = null;       for ( var i = 0; i < iDoc.pageItems.length; i++ ) {              //if(iDoc.pageItems[i].name == LegacyTextID && iDoc.pageItems[i].typename == "LegacyTextItem")        if(iDoc.pageItems[i].name == LegacyTextID)        {            result = iDoc.pageItems[i];                       if(result.typename=="GroupItem")            {                //WriteLog(LegacyTextID + " retrieve from a group item");                //Search the first textFrame available                 for (var y = 0; y < result.pageItems.length; y++) {                     var currentItem = result.pageItems[y];                      if(currentItem.typename=="TextFrame")                    {                        result = currentItem;                         break;                    }                }            }            if(result.typename=="TextFrame")            {                 break;            }                  }    }       return result;
}


//Log execution message in console and in a log file
function WriteLog(logContent)
{
    $.writeln(logContent);    try    {        //write in log persistent file        var logFile = new File(logPath);        logFile.open ("a");        logFile.writeln (logContent);         logFile.close();    }    catch(e)    {        $.writeln("Impossible to write information in log file: "+ logPath);    }
}

 

 

Then step2 - script2:

if(documents.length > 0)
{    //Retrieve document path    var docPath = documents[0].path;        //Init log path    var logPath = docPath + "/logs.txt";       //delete old  log file    var logFile= new File(logPath);    /*if(logFile.exists)    {
try
{
logFile.remove ();
}
catch(exc)
{
$.writeln("Impossible to delete old log file.");
$.writeln(exc);
}    }*/     WriteLog("Begin Export to SMG");         //WriteLog("Document path: " + docPath);    var docName = documents[0].fullName.displayName;    var currentdocPath = docPath + "/" +docName;    WriteLog("File path: " + currentdocPath);    var count = docName.search("^.*\.(src.svg)$");       var currentDoc = documents[0];       if(count<0)    {         WriteLog("Document extension is not correct. Only *.src.svg files are managed");    }    else    {         //Remove application alerts         app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;        //Retrieve ids of text to treat        var AiIDsList  = new Array();        var xmlBehaviorPath = currentdocPath.replace(".src.svg",".xml");        var xmlBehaviorFile = new File(xmlBehaviorPath);        if (xmlBehaviorFile.exists)        {            //Retrieve id to treat in svg exported            AiIDsList = RetrieveAiIDsFromXml(xmlBehaviorPath);        }        else        {            WriteLog("Behavior file doesn't exist.");        }           //Generate a mapping xml containing original id and exported id (+ justification and position to apply)        var mappingXmllUpdated = GenerateMappingXml(currentDoc,AiIDsList);        var idTable = new Array();        idTable = GetIdToClean(mappingXmllUpdated);                //var TopLeft=currentDoc.artboards[currentDoc.artboards.getActiveArtboardIndex()].artboardRect;         //WriteLog("artboard: " +TopLeft);                //Manage clipped elements        var groups = currentDoc.groupItems;        for( i=groups.length-1; i>=0; i--) {            var group = groups[i];            if( !group.clipped) {continue;}            if( group.pageItems.length < 2) {continue;}                       for( j=0; j < group.pathItems.length; j++) {                var cp = group.pathItems[j];                if( cp.clipping) {                    try                    {                        Unlock( group);                    }                    catch(exception)                    {                        WriteLog("Error => impossible to unlock following group: " & exception);                    }                    group.clipped = false;                    var g = currentDoc.groupItems.add();                    g.name= "groupNewClip"+ i;                    g.move( group, ElementPlacement.PLACEBEFORE);                    cp.move( g, ElementPlacement.PLACEATBEGINNING);                    group.move( cp, ElementPlacement.PLACEAFTER);                    g.clipped = true;                                       break;                }            }        }               //Export Current doc as final svg        var exportedDocPath = SaveToSvg(currentDoc);               //Replace exported id  by original id        CleanIdForSVG(exportedDocPath, idTable);               //Set matadata information in exported document        SetMetaForSVG(exportedDocPath);               //Set anchor for concerned item        CleanAnchorSVG(exportedDocPath,mappingXmllUpdated);    }    WriteLog("End Export to SMG");   
 }




/*********************************************************


Functions definition


**********************************************************/


//Unlock a given element
function Unlock( obj) {
if( !obj || obj===app) { return;}
Unlock( obj.layer); //v1.7
Unlock( obj.parent);
if( obj.locked) {
obj.locked = false;
}
if( obj.hidden) { //object and group
obj.hidden = false;
Unlock.aHidden.push( obj);
}
if( obj.visible===false) { //layer //v1.7
obj.visible = true;
Unlock.aHidden.push( obj);
}
}


//Export a given document to svg
function SaveToSvg(currentDoc)
{
        // Save as svg and close current doc.        var targetFile = getNewName();//retrieve the name to apply to the document to export        var svgSaveOpts = getSVGOptions();        currentDoc.artboards[0].artboardRect = currentDoc.visibleBounds;//Reposition the document viewbox        currentDoc.exportFile(targetFile, ExportType.SVG, svgSaveOpts);        currentDoc.close(SaveOptions.DONOTSAVECHANGES);               return targetFile;//Return path of exported document
 }


//Generate the name to apply to the document to export
function getNewName()
{
var ext, docName, newName, saveInFile, docName;
docName = documents[0].name;
    var nameSplitted = docName.split(".src.svg");
ext = '.svg'; // new extension for svg file
newName = "";     newName += nameSplitted[0];
newName += ext; // full svg name of the file

// Create a file object to save the svg
saveInFile = new File( documents[0].path + '/' + newName );


return saveInFile;
}


//Build defaut option for svg  saving
function getSVGOptions()
{
var svgSaveOpts = new ExportOptionsSVG();    //just using defaults aside from what's written below    //see http://cssdk.host.adobe.com/sdk/1.0/docs/WebHelp/references/csawlib/com/adobe/illustrator/ExportOptionsSVG.html    svgSaveOpts.compressed          = false;    svgSaveOpts.documentEncoding  = SVGDocumentEncoding.UTF8; //required for metadata...    svgSaveOpts.DTD = SVGDTDVersion.SVG1_1;    svgSaveOpts.includeFileInfo     = true; //to include metadata and title    svgSaveOpts.coordinatePrecision = 3;
//    svgSaveOpts.cssProperties       = SVGCSSPropertyLocation.PRESENTATIONATTRIBUTES;    svgSaveOpts.embedRasterImages   = true;
//    svgSaveOpts.fontType = SVGFontType.SVGFONT;    svgSaveOpts.preserveEditability = false;

return svgSaveOpts;
}




//Add meta information to final svg
function SetMetaForSVG(exportedDocPath)
{
    WriteLog("Final svg: " + exportedDocPath);        //Test if  final svg file exist    var finalSVGFile = new File(exportedDocPath);    if (!finalSVGFile.exists)    {        WriteLog("Svg file doesn't exist: " + exportedDocPath);    }    else    {        //Open and read content of the file        finalSVGFile.open ("r");        var xmlStr = finalSVGFile.read();        finalSVGFile.close();        var root;        try {            root = new XML(xmlStr);        } catch (e) {            WriteLog("\"SetMetaForSVG\" function=> impossible to open the exported document ");            return;        }           //var listElements = root.descendants ("metadata");        //WriteLog("Result=> " + root.elements("metadata")[0].elements().length());                      //Add onload attribute to root        root.@onload ="if(typeof(initSmg)!='undefined') initSmg( evt);";               //Retrieve first element in order to start insert at top of the document        var listElements = root.elements();        var firstElement = listElements[0];               //Create defs element        var xmlDefsStr = "<defs><script xlink:href=\"../smg.js\" language=\"JavaScript\"></script></defs>";        var xmlDefs = new XML(xmlDefsStr);               //Insert defs element        root.insertChildBefore (firstElement, xmlDefs);               //#######################################################################//        //Set the title               var isTitleOk = false;               //Try to reach metadata pavement        var qTextMetadata = new QName ("http://www.w3.org/2000/svg", "metadata");        var nodeTextListMetadata = root.descendants (qTextMetadata);               //Title element have been found        if(nodeTextListMetadata!="")        {            var qTextTitle = new QName ("http://www.w3.org/2000/svg", "pdf:Title");            var nodeTextListTitle = nodeTextListMetadata.descendants(qTextTitle);                       if(nodeTextListTitle=="")            {                qTextTitle=null;                qTextTitle = new QName ("http://www.w3.org/2000/svg", "dc:title");                nodeTextListTitle = nodeTextListMetadata.descendants(qTextTitle);            }                   if(nodeTextListTitle=="")            {                qTextTitle=null;                qTextTitle = new QName ("http://www.w3.org/2000/svg", "xap:Title");                nodeTextListTitle = nodeTextListMetadata.descendants(qTextTitle);            }            //Title element have been found            if(nodeTextListTitle!="")            {                var qTextLi = new QName ("http://www.w3.org/2000/svg", "rdf:li");                var nodeTextListLi = nodeTextListTitle.descendants(qTextLi);                               //Title value have been found                if(nodeTextListLi!="")                {                    //WriteLog("Result=> " + nodeTextListLi[0]);                                       //Try to reach title element                    var qText = new QName ("http://www.w3.org/2000/svg", "title");                    var nodeTextList = root.descendants (qText);                    if(nodeTextList!="")                    {                        //WriteLog("Result exist=> " + nodeTextList[0]);                        nodeTextList[0] = nodeTextListLi[0].toString();                    }                    else                    {                                               //Create title element                        var testEncode = encodeURIComponent (nodeTextListLi[0].toString());                        var xmlTitleStr = "<title>"+CleanSpecialCharactersOfXmlString(nodeTextListLi[0].toString())+"</title>";                        var xmlTitle = new XML(xmlTitleStr);                                               WriteLog("Create title element=> " + xmlTitle.toString());                                               root = root.insertChildBefore (firstElement, xmlTitle);                    }                    isTitleOk = true;                }            }        }        if(!isTitleOk)        {            WriteLog("Metadata: title has not been set");        }           //Open and edit content of the mapping xml file        finalSVGFile.open ("w");        finalSVGFile.write (root.toString());        finalSVGFile.close();    }
}


//Parse xml file in order to retrieve layer identifiant
function RetrieveAiIDsFromXml( sXML)
{
    var AiIDsTable = new Array();    WriteLog("RetrieveAiIDsFromXml for file: " + sXML);       //Open and read content of the file    var BehaviorFile = new File(sXML);    BehaviorFile.open ("r");    var xmlStr = BehaviorFile.read();    BehaviorFile.close();    var root = new XML(xmlStr);    var qText = new QName ("http://www.airbus.com/smg", "text");    var nodeTextList = root.descendants (qText);    //WriteLog("nodeTextList count: " + nodeTextList.length());    for( var i=0; i<nodeTextList.length(); i++) {  AiIDsTable[i] = nodeTextList[i].@gref;    }    var qTextExt = new QName ("http://www.airbus.com/smg", "textex");    var nodeTextExList = root.descendants (qTextExt);    //WriteLog("nodeTextList count: " + nodeTextList.length());    for( var i=0; i<nodeTextExList.length(); i++) {  AiIDsTable[nodeTextList.length() + i] = nodeTextExList[i].@gref;    }  return AiIDsTable;
}


//Generate mapping file
function GenerateMappingXml(currentDoc,AiIDsList)
{
    var root = new XML("<smgBankKeys></smgBankKeys>");       for (var c = 0; c < AiIDsList.length; c++) {        var currentProperty = new XML("<property></property>");               var aiIDvalue = AiIDsList[c];        var aiIDcorrected = aiIDvalue.toString().replace (/_/g, ' ');        //WriteLog("Element value: " + aiIDcorrected);        var elementResult = getElementFromDocument(currentDoc,aiIDcorrected);        if(elementResult==null)        {            WriteLog("Element not found for : " + aiIDcorrected+ "  *** original value from behavior=> " + aiIDvalue);        }        else        {            currentProperty.@aiID = AiIDsList[c];                       if(elementResult.name=="")            {                //WriteLog(aiIDcorrected + " not  used directly");                currentProperty.@svgID = aiIDvalue;            }            else            {                //WriteLog("Element found for (from result) : " + elementResult.name);                currentProperty.@svgID = aiIDvalue+"_1_";            }                   //Retrieve text element width            currentProperty.@Width = elementResult.width;                       if(elementResult.paragraphs != null  && elementResult.paragraphs.length>0)            {                //WriteLog("Justification=> " + elementResult.paragraphs[0].paragraphAttributes.justification);                currentProperty.@Justification = elementResult.paragraphs[0].paragraphAttributes.justification;                     //WriteLog("Anchor X=> " + elementResult.anchor[0]);                currentProperty.@anchorPositionX = elementResult.anchor[0];                //WriteLog("Anchor Y=> " + elementResult.anchor[1]);                currentProperty.@anchorPositionY = elementResult.anchor[1];                                // get alignment correction                if(elementResult.paragraphs[0].paragraphAttributes.justification == Justification.CENTER) {                    currentProperty.@TranslateValue=Round(elementResult.width / 2);                    currentProperty.@AnchorValue= "middle";                } else                if( elementResult.paragraphs[0].paragraphAttributes.justification  == Justification.RIGHT) {                    currentProperty.@TranslateValue= Round(elementResult.width);                    currentProperty.@AnchorValue= "end";                } else {                    currentProperty.@TranslateValue= 0;                    currentProperty.@AnchorValue= "start";                }            }            root.appendChild (currentProperty);        }    }          return root;
}


function GetIdToClean(root)
{
    var idTable = new Array();    //WriteLog("xml details: " + root.toString ());    var componentList = root.xpath("/smgBankKeys/property");    var componentsLength = componentList.length();       var index = 0;    for (var c = 0; c < componentsLength; c++) {        var aiID = componentList[c].@aiID;        var svgID = componentList[c].@svgID;        if(aiID!=svgID)        {            idTable[index] = new Array();            idTable[index][0]= componentList[c].@aiID;            idTable[index][1]= componentList[c].@svgID;            index++;        }    }    return idTable;
}


//Search an element for a document
function getElementFromDocument(iDoc,elementID)
{
    var result = null;       for ( var i = 0; i < iDoc.pageItems.length; i++ ) {              //if(iDoc.pageItems[i].name == LegacyTextID && iDoc.pageItems[i].typename == "LegacyTextItem")        if(iDoc.pageItems[i].name == elementID)        {            result = iDoc.pageItems[i];            if(result.typename=="GroupItem")            {                try                {                    /*RMA 13112013  correction textframe retrieving for group items                        //From GroupItem, got to first GroupItem and then to the first textFrame                        if(result.pageItems.length>0 && result.pageItems[0].textFrames != undefined)                        {                            WriteLog("getElementFromDocument=> use result.pageItems[0].textFrames[0] for "+elementID);                            result = result.pageItems[0].textFrames[0];                        }                        else                        {                            WriteLog("getElementFromDocument=> use result.textFrames[0] for "+elementID);                            result = result.textFrames[0];                        }*/                                       //From GroupItem, got to first GroupItem and then to the first textFrame                    if(result.textFrames != undefined && result.textFrames.length>0)                    {                        WriteLog("getElementFromDocument=> group identified use result.textFrames[0] for "+elementID);                        result = result.textFrames[0];                    }                    else                    {                         if(result.pageItems.length>0 && result.pageItems[0].textFrames != undefined)                        {                            WriteLog("getElementFromDocument=> group identified use result.pageItems[0].textFrames[0] for "+elementID);                            result = result.pageItems[0].textFrames[0];                        }                        else                        {                            WriteLog("getElementFromDocument=> " + elementID + " group identified but no textFrame is available");                            result = null;                        }                    }                              }                catch (err) {                    WriteLog("\"getElementFromDocument=>\" function=> error occured: " +err.message);                    result = null;                }                break;            }            if(result.typename=="TextFrame")            {                WriteLog("getElementFromDocument=> " + elementID + " TextFrame has  been identified ");                 break;            }                  }    }    return result;
}


//Clean id _1_ ref in the final SVG
function CleanIdForSVG(exportedDocPath, idTable)
{
    if(idTable.length>0)    {        //WriteLog("Final svg: " + exportedDocPath);                //Test if  final svg file exist        var finalSVGFile = new File(exportedDocPath);        if (!finalSVGFile.exists)        {            WriteLog("Svg file doesn't exist: " + exportedDocPath);        }        else        {            //Open and read content of the file            finalSVGFile.open ("r");            var xmlStr = finalSVGFile.read();            finalSVGFile.close();                   var root ;            try            {                root= new XML(xmlStr);             } catch (e) {                WriteLog("\"SetMetaForSVG\" function=> impossible to open the exported document ");                return;            }                       for ( var i = 0; i < idTable.length; i++ )            {                 var aiID= idTable[i][0];                var svgID= idTable[i][1];                //Test if element  exist                             var firstIndex = xmlStr.indexOf("\"" + svgID + "\"");//Compare first result and last result in oder to check if only one result is retrieved                var lastIndex = xmlStr.lastIndexOf("\"" + svgID + "\"");                if(firstIndex>-1)                {                    if(firstIndex!=lastIndex)                        WriteLog("CleanId => Too many element found for id: "  + svgID);                    else                    {                        WriteLog("Replace id: "  + svgID + " => " +aiID);                        xmlStr = xmlStr.replace ("\"" + svgID + "\"","\"" + aiID + "\"");                    }                }                else                {                    WriteLog("CleanId => No entry found for id: "  + svgID);                }            }            //Open and edit content of the mapping xml file            finalSVGFile.open ("w");            finalSVGFile.write (xmlStr);            finalSVGFile.close();        }    }    else    {        WriteLog("CleanId => No svg ID to clean");    }
}


function CleanAnchorSVG(exportedDocPath, root)
{
        var componentList = root.xpath("/smgBankKeys/property");        var componentsLength = componentList.length();               for (var c = 0; c < componentsLength; c++) {            var aiID = componentList[c].@aiID;            var justification = componentList[c].@Justification;            var translateWidthValue = componentList[c].@TranslateValue;            if(justification != Justification.LEFT.toString())            {                SetAnchorSVG(exportedDocPath,aiID,justification,translateWidthValue);                //WriteLog("Anchor to clean for: " + aiID + "=>" + justification);            }        }   
}




function SetAnchorSVG(exportedDocPath,aiID,justification,translateWidthValue)
{
    //WriteLog("Final svg: " + exportedDocPath);        //Test if  final svg file exist    var finalSVGFile = new File(exportedDocPath);    if (!finalSVGFile.exists)    {        WriteLog("Svg file doesn't exist: " + exportedDocPath);    }    else    {        var buffer = new Array();        //Open and read content of the file        var finalSVGFile = new File(exportedDocPath);        finalSVGFile.open ("r");               var data;        var index = 0;        while (data = finalSVGFile.readln())        {                       var result = data.search ("id=\""+aiID+"\"");            if(result>0)            {                //WriteLog("*****************Match file for: " + aiID + " *****************");                 buffer[index] = GenerateStyleForAnchor(data,justification,translateWidthValue);            }            else            {                buffer[index] = data;                //finalSVGFileCorrected.writeln (data);            }                         index++;        }        finalSVGFile.close();               //Open and read content of the file        var finalSVGFileCorrected = new File(exportedDocPath);        finalSVGFileCorrected.open ("w");                for (var c = 0; c < buffer.length; c++) {            finalSVGFileCorrected.writeln (buffer[c]);        }              finalSVGFileCorrected.close();               //finalSVGFileCorrected.rename(exportedDocPath);               /*finalSVGFile.open ("w");        finalSVGFile.write (buffer);        finalSVGFile.close();*/    }
 }


function GenerateStyleForAnchor(row,justification,translateWidthValue)
{      var result;       var styleValue;    var transformValue = "translate("+translateWidthValue+",0) ";       //WriteLog("original: " + justification);    switch(justification.toString())    {        case Justification.RIGHT.toString():          styleValue = "text-anchor:end;";          break;        case Justification.CENTER.toString():          styleValue = "text-anchor:middle;";          break;        default:          styleValue = "text-anchor:start;";          transformValue="";//force reset of position    }    //WriteLog(styleValue);    //Edit style property    var searchValue = "style=\"";    var index = row.search (searchValue);    var tagEndIndex = row.search (">");    var tagStartIndex = row.search ("<");    if(index<0)    {        //search first availble space        index = row.search(" ");        if (index < tagStartIndex)        {            var offset = index;            while (index < tagStartIndex)            {                offset++;                index = row.indexOf (" ", offset);            }        }               startString = row.substring (0, index+1);        endString = row.substring (index+1, row.length);        styleValue = " style=\"" + styleValue + "\" ";    }    else    {        if (index > tagEndIndex)        {            //search first availble space            index = row.search (" ");            if (index < tagStartIndex)            {                var offset = index;                while (index < tagStartIndex)                {                    offset++;                    index = row.indexOf (" ", offset);                }            }            startString = row.substring (0, index+1);            endString = row.substring (index+1, row.length);            styleValue = " style=\"" + styleValue + "\" ";        }        else        {            startString = row.substring (0, index+searchValue.length);            //WriteLog(startString);            endString = row.substring (index+searchValue.length, row.length);            //WriteLog(endString);        }    }       result = startString+styleValue+endString;       //Reset infos    index=0;    startString="";    endString="";       //Edit transform property    if(transformValue!="")    {        searchValue = "transform=\"";        index = result.search (searchValue);        tagEndIndex = result.search (">");               if(index<0)        {            //search first availble space            index = result.search (" ");            if (index < tagStartIndex)            {                var offset = index;                while (index < tagStartIndex)                {                    offset++;                    index = result.indexOf (" ", offset);                }            }            startString = result.substring (0, index+1);            endString = result.substring (index+1, result.length);            transformValue = " transform=\"" + transformValue + "\" ";        }        else        {            if (index > tagEndIndex)            {                //search first availble space                index = result.search (" ");                if (index < tagStartIndex)                {                    var offset = index;                    while (index < tagStartIndex)                    {                        offset++;                        index = result.indexOf (" ", offset);                    }                }                startString = result.substring (0, index+1);                endString = result.substring (index+1, result.length);                transformValue = " transform=\"" + transformValue + "\" ";            }            else            {                startString = result.substring (0, index+searchValue.length);                //WriteLog(startString);                endString = result.substring (index+searchValue.length, result.length);                //WriteLog(endString);            }        }        result = startString+transformValue+endString;    }       return result;
}


function Round( n) {
    return Math.round( n * 100) / 100;
}


function CleanSpecialCharactersOfXmlString(xmlString)
{
    var result = xmlString;    result = result.replace ('&', "&amp;");    result = result.replace ('<', "&lt;");    result = result.replace ('>', "&gt;");    result = result.replace ('"', "&quot;");    result = result.replace ("'", "&#39;");    return result;
}


//Log execution message in console and in a log file
function WriteLog(logContent)
{
    $.writeln(logContent);    try    {        //write in log persistent file        var logFile = new File(logPath);        logFile.open ("a");        logFile.writeln (logContent);         logFile.close();    }    catch(e)    {        $.writeln("Impossible to write information in log file: "+ logPath);    }
}

 

With CC, it now results to a null file.


Viewing all articles
Browse latest Browse all 84

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>