Save document to different folder - javascript

below is my test directory structure:
I have made a script which works on a psd file in the finals folder. My aim is to save it to the tifs folder. This is the code i have:
app.activeDocument.saveAs(file."../tifs", TiffSaveOptions, true, Extension.LOWERCASE);
I am well and truly stuck. I have tried so many combinations and everything is throwing an error. I just want to come out of the finals folder, and then go into the tifs folder and save.
any help would be much appreciated. :)

You've not set up your file path correctly. I suspect "../tifs" isn't working as you'd hoped. Here it is in full.
// Flatten the tiff
app.activeDocument.flatten();
// set up the new directory
// make sure you change this or
// have a folder in c:\testpsd\tifs
var myFolder = "c:\\testpsd\\tifs"; // add extra escape slash
// get the documents name
var myFileName = app.activeDocument.name;
// remove it's extension
var myDocName = myFileName.substring(0,myFileName.length -4);
// set the new filename and path
var myFilePath = myFolder + "/" + myDocName + ".tiff";
// tiff file options
var tiffFile = new File(myFilePath);
tiffSaveOptions = new TiffSaveOptions();
tiffSaveOptions.byteOrder = ByteOrder.MACOS;
tiffSaveOptions.layers = false;
tiffSaveOptions.transparency = true;
tiffSaveOptions.alphaChannels = true;
tiffSaveOptions.embedColorProfile = false;
tiffSaveOptions.imageCompression = TIFFEncoding.TIFFLZW;
tiffSaveOptions.saveImagePyramid = false;
// finally save out the document
activeDocument.saveAs(tiffFile, tiffSaveOptions, false, Extension.LOWERCASE);

Related

Trying to create a Google Drive Script to copy and move files

I'm horrible at coding so I'm sure this will need some work.
My Problem: My company does work for a lot of other companies (example Drive hierarchy photo attached). Each company we work with gets their own folder that is nested under the folder 'Shirts for other companies". We put all their assets into these folders (logos, mocks, quotes).
We want to build a script that will look into the individual company folders and take any file that starts with the word Mock and automatically copy it and put it into the database folder found in the picture below.
Here is the script have so far. but I'm having trouble getting into the subfolders (ford tshirts and designs). Not only that, but if it runs everyday the script will keep duplicating the files it has duplicated in the past which I want to avoid.
Script:
Function getTheFiles() {
var dApp = DriveApp;
var folderIter = dApp.getFolderByName("Shirts for other companies");
var folder = folderIter.next();
var filesIter = folder.getFiles();
var dataBase = folder.getFoldersByName("database1").next();
var i = 1;
while(filesIter.hasNext()) {
var file = filesIter.next();
var filename = file.getName();
if(filename = "mocking") {
file.makeCopy(dataBase);
}
logger.log(filename);
i++;
}
If I understood you correctly, you want to:
Copy all files from the different subfolders inside a folder called "Shirts for other companies", that start with the word mock, to the Database folder (which is also inside the main folder).
Avoid files getting copied many times.
If that's the case, you could do the following:
Search for all files in each subfolder of the main folder that start with mock, excluding the files inside Database folder. For this, you iterate through all files in each subfolder (after checking the subfolder is not named Database folder. For each file, you check that the name start with mock, using the method substring.
To keep track of which files are copied, and so avoid making duplicates, you can use PropertiesService, which can store key-value pairs. The id of every copied file is copied to the script property, and then, the next time the script runs, it checks whether the id is in the property. If that's the case, the file doesn't get copied again. One thing to notice is that script properties can only store strings, so that arrays have to be converted to a string every time we want to store a new id (via toString, and back to an array, via split.
The function below does all these things (check inline comments for more details):
function copyFiles() {
var mainFolder = DriveApp.getFoldersByName("Shirts for other companies").next();
var folders = mainFolder.getFolders(); // Get folder iterator from main folder
var databaseFolderName = "Database folder"; // You database folder name
var databaseFolder = mainFolder.getFoldersByName(databaseFolderName).next(); // Get databse folder
var idsArray = []; // Array to store the ids of the copied files
while (folders.hasNext()) { // Iterate through each folder in the main folder
var folder = folders.next();
if (folder.getName() !== databaseFolderName) { // Check current folder is not the database folder
var files = folder.getFiles();
while (files.hasNext()) { // Iterate through each file in each subfolder
var file = files.next();
if (file.getName().substring(0, 4).toLowerCase() === "mock") { // Check that file name starts with "mock"
// Get ids of the files that were copied in previous executions:
var key = "copied-ids";
var scriptProperties = PropertiesService.getScriptProperties();
var ids = scriptProperties.getProperty(key);
if (ids) idsArray = ids.split(",");
else ids = "";
// Get current file id:
var id = file.getId();
// Check that current file id is not in properties (not copied before):
if (idsArray.indexOf(id) === -1) {
file.makeCopy(databaseFolder); // Copy file to database folder
idsArray.push(id); // Add file id to the array of copied files
}
ids = idsArray.toString();
scriptProperties.setProperty(key, ids);
}
}
}
}
}
Reference:
PropertiesService
String.prototype.substring()
Array.prototype.toString()
String.prototype.split()
I hope this is of any help.
This function would search your entire Google Drive for files starting the the letter Mock and put Name, url, id, type (folder or file) into the active spreadsheet and tab named MoclList;
function getAllMocks() {
var ss=SpreadsheetApp.getActive();
var sh1=ss.getSheetByName('MocksList');
sh1.clearContents();
sh1.appendRow(['Name','Url','Id','Type']);
getFnF();
SpreadsheetApp.getUi().alert('Process Complete')
}
var level=0;
function getFnF(folder) {
var folder= folder || DriveApp.getRootFolder();
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('MocksList');
var files=folder.getFiles();
while(files.hasNext()) {
var file=files.next();
if(file.getName().toLowerCase().slice(0,4)=='mock') {
var firg=sh.getRange(sh.getLastRow() + 1,level + 1);
firg.setValue(file.getName());
firg.offset(0,1).setValue(Utilities.formatString('=HYPERLINK("%s","%s")',file.getUrl(),'FILE: ' + file.getName()));
firg.offset(0,2).setValue(file.getId());
firg.offset(0,3).setValue('File');
}
}
var subfolders=folder.getFolders()
while(subfolders.hasNext()) {
var subfolder=subfolders.next();
var forg=sh.getRange(sh.getLastRow() + 1,level + 1);
forg.setValue(subfolder.getName());
forg.offset(0,1).setValue(Utilities.formatString('=HYPERLINK("%s","%s")',subfolder.getUrl(),'FOLDER: ' + subfolder.getName()));
forg.offset(0,2).setValue(subfolder.getId());
forg.offsert(0,3).setValue('Folder');
//level++;
getFnF(subfolder);
}
//level--;
}

Rename all files in google drive by using google script

I want to rename my all Audio files in particular folder in my drive by using google script.
How to get original name of file? And replace with new name that will erase first 23 words and remain all name as it was. I didn't understand how to do that.
I try following script.
​ function non_native_file_name_changer(folderID,fileName,fileType,iterator) {
var folder = DriveApp.getFolderById('ID');
var files = folder.getFilesByType(fileType);
var count = 1
while(files.hasNext()){
var file = files.next()
if(iterator === true){
file.setName(file.getName().slice(-23));
}else{
file.setName(fileName);
};
};
};
function start(){
var folder_ID = "ID";
var file_name = "Audio";
var file_type = "audio/amr";
var have_a_count = true;
var go = non_native_file_name_changer(folder_ID,file_name,file_type,have_a_count);
};
This not work...
Please help.
To call all files from folder but no run.
Please help.
You say you want the files from a specific folder but you didn't open a specific folder. What happens if you use
var id = "xxxxxxxxxxxxxx";
var files = DriveApp.getFolderById(id).getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}

Google script to get folder names within a parent folder

I need to get the names and URLs of the folders in a specified folder.
This is my attempt:
// set the folder to pull folder names from
var DDparentid = "IDhere";
var DDparent = DriveApp.getFolderById(DDparentid);
var DDfolders = DDparent.getFolders();
// iterate through folders in the folder
while (DDfolders.hasNext()) {
var folder = DDfolders.next();
// get folder name
Logger.log(folder.getName());
var DDnames = folder.getName();
// get the url
Logger.log(folder.getUrl());
var DDURLs = folder.getUrl();
}
This works for get file URLs, but I believe that folders are treated differently, and getfolder is used differently. I get an error stating that a string is not suitable in DriveApp.getfolder(). How should I be using getfolder?
EDITED: this runs, buit doesn't actually pull URLs or folder names. Both variables are undefined, but there are no errors.
You can try this :
var parentFolderId = "xxxxxxxIDxxxxxxx";
var parentFolder = DriveApp.getFolderById(parentFolderId);
var folders = parentFolder.getFolders();
var folder;
// iterate through folders in the folders fetched from parent folder
while (folders.hasNext()) {
folder = folders.next();
// get folder name
Logger.log(folder.getName());
// get the url
Logger.log(folder.getUrl());
}
This is an un-tested code, let me know if any issue arises I'll be happy to help us.
Thanks
Below lists all subfolder name and URL for specified folder:
function listSubFoldersInFolder(id) {
var dfolder = DriveApp.getFolderById('ENTER_PARENT_FOLDER_ID_HERE');
var contents = dfolder.getFolders();
var file;
var name;
var sheet = SpreadsheetApp.getActiveSheet();
var link;
sheet.clear();
sheet.appendRow(["Name", "Link"]);
while(contents.hasNext()) {
file = contents.next();
name = file.getName();
link = file.getUrl();
data = [name, link]
sheet.appendRow(data);
}
};

Check if file exists with different extension?

I am starting out in photoshop with a .tif file. I run a script which adds some layers etc and then i save the file as a .psd in a new folder.
The problem i am having is checking to see if a .psd file already exists with the same name. My goal is to simply close down the .tif file without saving if a .psd with the same name appears in the folder.
Here is my save code:
//Save document
var savePath = Folder(doc.path.parent) + "/new_folder/";
saveFile = new File(savePath);
saveOptions = new PhotoshopSaveOptions;
saveOptions.embedColorProfile = true;
if ( WHAT SHOULD I BE ASKING HERE? ) {
doc.saveAs(saveFile, saveOptions, false, Extension.LOWERCASE);
} else {
doc.close(SaveOptions.DONOTSAVECHANGES);
}
I'm stuck with what add to the if function? I've tried .exists but it's not working because the current file is still in .tif mode and hasn't saved to .psd yet. So it just keeps on saving and overwriting the previous saved .psd
Any help would be most welcome. :)
EDIT:
Thought i had it working with this but still no luck:
//Strip .tif and add .psd to file name
var docName = doc.name;
PSDName = docName.substr(0,docName.length-3);
PSDName = PSDName + "psd";
//Save document
var savePath = Folder(doc.path.parent) + "/new_folder/";
saveFile = new File(savePath);
saveOptions = new PhotoshopSaveOptions;
saveOptions.embedColorProfile = true;
var savedFile = savePath + "/" + PSDName
if (! savedFile.exists ) {
doc.saveAs(saveFile, saveOptions, false, Extension.LOWERCASE);
} else {
doc.close(SaveOptions.DONOTSAVECHANGES);
}
the if statement is returning false every time and the doc is not saving. If i take away the ! it saves every time.
Make a new variable with the filename that you want to test - i.e. the name of the .PSD file and use that. For example, strip off the TIF and replace it with PSD then use .exists.
var ImageName = activeDocument.name;
PSDName = ImageName.substr(0,ImageName.length-3); // Strip "TIF" from end
PSDName = PSDName + "psd"; // Add on "PSD" instead
If you need to debug your script, you can do something like this:
// Change Debug=1 for extra debugging messages, Debug=0 for no messages
var Debug=1;
...
if(Debug)alert(PSDName);
...
if(Debug)alert("File exists");

Save file in Illustrator with Javascript

I'm trying to save a file in Illustrator using Javascript but I keep getting an error.
Here is what works, but is not what I want:
// save as
var dest = "~/testme.pdf";
saveFileToPDF(dest);
function saveFileToPDF (dest) {
var doc = app.activeDocument;
if ( app.documents.length > 0 ) {
var saveName = new File ( dest );
saveOpts = new PDFSaveOptions();
saveOpts.compatibility = PDFCompatibility.ACROBAT5;
saveOpts.generateThumbnails = true;
saveOpts.preserveEditability = true;
alert(saveName);
doc.saveAs( saveName, saveOpts );
}
}
The var "dest" saves the file to the root of my Mac user account. I simply want to save the file relative to the source document in a subfolder, so I tried this:
var dest = "exports/testme.pdf";
This brings up a dialogue with ".pdf" highlighted, properly awaiting input inside the "exports" folder that I already created. I can type something and it will save, but it ignores the file name "testme.pdf" that was specified in the code. I can type "cheese" over the highlighted ".pdf" it knows I want, and it will save "cheese.pdf" in the folder "exports".
I also tried these with no luck:
var dest = "exports/testme";
var dest = "/exports/testme.pdf";
var dest = "testme.pdf";
etc., etc.
What am I missing?
To use saveAs without a dialog popping up, you need to use the global property userInteractionLevel:
var originalInteractionLevel = userInteractionLevel;
userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
...
userInteractionLevel = originalInteractionLevel;
Since you want to save relative to your document, so first find the path for your current document as follows
var path = app.activeDocument.path;
var dest = path + "/exports/testme.pdf";
You can also check whether exports folder exists or not if not you can create with script as follows
var path = app.activeDocument.path;
var exportFolder = Folder(path + "/exports");
if(!exportFolder.exists){
exportFolder.create();
}
var dest = exportFolder + "/testme.pdf";

Categories