Save file in Illustrator with Javascript - 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";

Related

Folder ID displays in Logger but the value wont allow me to move file to said folder ID

Okay so I have a sheet that I use to keep track of tips at work. Since its a shared sheet to keep it simple I just copy the sheet when its done and then archive the copied sheet to a subfolder based on the year.
All the code works perfect except when I try to move the copied sheet to the folder that I want.
Since I want to keep this as automatted as possible I have code to read the date within the sheet and either make a new folder for the year or move the file to the year folder that already exist.
For some reason the file will not move to the folder I want and I've tried multiple ways: within the 'makeCopy' function as well as the DriveApp.getFileById().moveTo();
Here is my code, error runs at bottom of code:
//Create folder if does not exists only
function createFolder(folderID, folderName){
var parentFolder = DriveApp.getFolderById(folderID);
var subFolders = parentFolder.getFolders();
var doesntExists = true;
var newFolder = '';
// Check if folder already exists.
while(subFolders.hasNext()){
var folder = subFolders.next();
//If the name exists return the id of the folder
if(folder.getName() === folderName){
doesntExists = false;
newFolder = folder;
return newFolder.getId();
};
};
//If the name doesn't exists, then create a new folder
if(doesntExists == true){
//If the file doesn't exists
newFolder = parentFolder.createFolder(folderName);
return newFolder.getId();
};
};
function start(){
//Parent folder (Location)
var FOLDER_ID = '1yinFsKfMP3_pWbM7BnOKcNRk-BDcty6E';
//Add the name of the folder here (Year of the sheet):
var year = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Instructions").getRange('L2').getDisplayValue();
var NEW_FOLDER_NAME = year;
//Create a new folder if a folder for the year doesnt exist (reverts to function:createFolder)
var myFolderID = createFolder(FOLDER_ID, NEW_FOLDER_NAME);
//Get the file ID of the parent file (Tip Tracker)
var getID = SpreadsheetApp.getActive().getId();
//Get the current name of the Tip Tracker (with dates)
var getName = SpreadsheetApp.getActive().getName();
//Create copy of Tip Tracker to be filed accordingly
var newFileID = DriveApp.getFileById(getID).makeCopy(getName + " ").getId();
var getNewFile = DriveApp.getFileById(newFileID);
getNewFile.moveTo(myFolderID);
Logger.log(newFileID);
Logger.log(myFolderID);
};
Try creating a getMyFolder as you did with getNewFile and moveTo the folder versus the ID.
const myFolder = DriveApp.getFolderById(myFolderID)
// ...
getNewFile.moveTo(myFolder)
File.moveTo(folder) takes a Folder, not an ID.

Blob would be exported before changes are made to the files

I wrote a google script to generate resume and cover letter faster. It does the following
use ui.prompt to input content
create a folder and copy docs to the folder
replace keyword to content
convert docs to pdf in the folder
However, somehow the docs would be converted to PDFs before the keywords were replaced.
I have tried below but to no avail:
async awaits to wait for the main function before starting exporting PDFs
use utilities.sleep() to delay the exports
I have the main function and export function below for your information.
function jobHuntAutomation() {
//UI prompts for documents
var ui = DocumentApp.getUi();
var companyName = ui.prompt('Cover Letter', 'Enter Company Name: \n', ui.ButtonSet.OK);
var positionName = ui.prompt('Cover Letter', 'Enter Position Name: \n', ui.ButtonSet.OK);
var hiringManagerName = ui.prompt('Cover Letter', 'Enter Hiring Manager Name: \n', ui.ButtonSet.OK);
//Create some file name strings
var folderName = `${companyName.getResponseText()}_${positionName.getResponseText()}`
var coverLetterName = `${companyName.getResponseText()}_${positionName.getResponseText()}_Coverletter`
var resumeName = `${companyName.getResponseText()}_${positionName.getResponseText()}_Resume`
//Get new folder object and Id
var newFolder = DriveApp.getFolderById(mainFolderId).createFolder(folderName);
var newFolderId = newFolder.getId();
var newFolderUrl = newFolder.getUrl()
//Make a copy
console.log('Making Copies')
DocumentApp.getUi().showModalDialog(modalMessage('Making Copies...'), 'Status');
var coverLetterId = DriveApp.getFileById(coverLetterTemplateId).makeCopy(coverLetterName, newFolder).getId();
var resumeId = DriveApp.getFileById(resumeTemplateId).makeCopy(resumeName, newFolder).getId();
//Status
DocumentApp.getUi().showModalDialog(modalMessage('Updating Content...'), 'Status');
//Get the coverLetter document body as a variable
var coverLetterBody = DocumentApp.openById(coverLetterId).getBody();
//Get the resume document body as a variable
var resumeBody = DocumentApp.openById(resumeId).getBody();
//Update Content
doc.replaceText(keyword, input.getResponseText())
.
.
.
//you get the idea
//export PDFs
convertToPdf(resumeId, newFolder)
convertToPdf(coverLetterId, newFolder)
DocumentApp.getUi().showModalDialog(folderLink(newFolderUrl), 'Link');
}
function convertToPdf(fileId, dest) {
doc = DriveApp.getFileById(fileId);
docblob = doc.getAs('application/pdf');
console.log(`Converting ${doc.getName()}...`)
/* Add the PDF extension */
docblob.setName(doc.getName() + ".pdf");
// add file to the dest Folder
dest.createFile(docblob);
}
It would be much appreciated if someone knows a solution to export PDFs AFTER the keywords are replaced. TIA
I figured it out. the docs need to be saveAndClose() before exporting so the changes would be flushed

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());
}

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 document to different folder

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);

Categories