I'm using the following script to export all items / per page from an indesign document to jpg. This script also crops all items to their size given by the container in indesign.
I would like to limit this script to export only all "placed images", because I only need the images. At the moment I get also all rectangular objects like text boxes and so on.
#target InDesign
//set properties for export to your needs
with(app.jpegExportPreferences){
antiAlias = true;
embedColorProfile = false;
exportResolution = 300;
jpegColorSpace = JpegColorSpaceEnum.RGB; //JpegColorSpaceEnum.CMYK, JpegColorSpaceEnum.GRAY r/w One of RGB, CMYK or Gray
jpegQuality = JPEGOptionsQuality.HIGH; //JPEGOptionsQuality.LOW, JPEGOptionsQuality.MEDIUM, JPEGOptionsQuality.HIGH, JPEGOptionsQuality.MAXIMUM r/w The compression quality.
jpegRenderingStyle = JPEGOptionsFormat.BASELINE_ENCODING; // JPEGOptionsFormat.PROGRESSIVE_ENCODING r/w The rendering style.
simulateOverprint = true;
}
//doc has to be saved once
var theDoc = app.activeDocument;
var docName = theDoc.name;
var docShortName = docName.replace(/.indd/, '')
var docPath = '' + theDoc.fullName;
var docContainerPath = docPath.replace(docName, '')
var destPath = docContainerPath + '/' + docShortName + '_jpgExport/'
if(Folder(destPath).create() != true){alert('Could not create targetfolder.'); exit();}
var pageItems = theDoc.pageItems.everyItem().getElements();
l = pageItems.length;
counter = 0;
for(var i = 0; i < l; i++){
counter = counter + 1;
var singlePageItem = pageItems[i];
currParentPage = singlePageItem.parentPage;
if(currParentPage == null){parentPageNumber = 'pasteboard'}else{parentPageNumber = singlePageItem.parentPage.name; }
newFile =new File(destPath + 'page_' + parentPageNumber + '_' + 'item_' + counter + '.jpg');
if(singlePageItem.exportFile(ExportFormat.JPG, newFile) === false){alert(newFile + ' could not write jpg-File.')}
}
If I understand you correctly, in place of:
var pageItems = theDoc.pageItems.everyItem().getElements();
you could use:
var pageItems = theDoc.allGraphics;
which would grab all the graphic elements instead of every pageItem. Is this what you were thinking?
EDIT: You may need to grab the parent element of every graphic element in order to export them.
Related
I have script that
PSD (activeDocument) in "3.Working folder saves jpg in draft folders in directory "../UserNameJobName/4.WIP/"
The problem is that everything works fine until I want to to create third draft folder (draft003). Then it saved again activeDocument in the same jpg file in draft002, instead of creating new folder draft003 and saving there respectivly. It seams that var draftCounter can't be higher than 2 value. I'm not sure where is a bug. What I know in photoshop CC it works without any problems.
[Link to folder structure zip]
https://www.dropbox.com/s/kbalzsubs2477jy/191130_WARGAMES_LUKKAR.zip?dl=0
Main file directory pic
Draft directory pic
code
#target photoshop;
var wipCounter = 1;
var fileNotFound = true;
main();
function main(){
//Get file information
var doc = app.activeDocument;
var docName = doc.name;
var docPath = doc.path;
//Get the percentage to scale by
var scaleValue = prompt("Enter the WIP JPEG scale percentage", "100");
//Figure out the location of the WIP folder
var savePath = docPath.toString();
savePath = savePath.slice(0,-10);
savePath = savePath + "/4.WIP/";
var currDoc = docName.toString();
currDoc = currDoc.slice(0,-4);
//global variables are defined here
//Look at the WIP folder and run a search for anything containing the word "draft"
//Define the location of the WIP folder
var inWIPFolder = new Folder(savePath);
//Look in each folder and create an array containing all of the information
var fileList = inWIPFolder.getFiles();
// Look at each array and sort the info out
for(var a=0; a<fileList.length; a++) {
//Exclude anything that is not a folder
if(fileList[a] instanceof Folder) {
//convert each foldername to string for editing
var fileName = fileList[a].toString();
var draftSearch = fileName.search("draft");
if(draftSearch > -1) {
var draftCounter = fileName.slice(draftSearch);
if(fileNotFound == true) {
searchDraftFolder(draftCounter, savePath, currDoc);
}
}
}
}
//Formatting the numbers
if(wipCounter < 10){
wipCounter = "00" + wipCounter.toString();
}else if(wipCounter >= 10 && wipCounter < 100) {
wipCounter = "0" + wipCounter.toString();
}
//Define the path of the draft folders
savePath = Folder(savePath +"/draft" + wipCounter);
//Check to see if the draft folders exists. If not, make one
if(!savePath.exists){
savePath.create();
}
//Define the WIP file name with the incremental counter
var wipFileName =savePath + "/" + currDoc + "_WIP" + wipCounter + ".jpg";
//Resize the file
doc.selection.selectAll();
var blankLayer = doc.artLayers.add();
blankLayer.name = "blankLayer";
doc.selection.copy(true);
doc.layers.getByName("blankLayer").remove();
//Make new doc to paste into
app.preferences.rulerUnits = Units.PIXELS;
//arguments are: Width, Height, resolution, filename, colourspce, documentfill
app.documents.add(UnitValue(doc.width, "PX"), UnitValue(doc.height, "PX"), doc.resolution, wipFileName, NewDocumentMode.RGB, DocumentFill.TRANSPARENT,1);
app.activeDocument.paste();
app.activeDocument.resizeImage(UnitValue(scaleValue, "PERCENT"), null, null, ResampleMethod.BICUBICSHARPER);
//Save a RGBJpeg
jpegFileSaver(app.activeDocument, new File(wipFileName), 10);
//Close the new document down
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
//Deselect
doc.selection.deselect();
alert(currDoc + "WIP" + wipCounter + " saved.");
}
function searchDraftFolder(draftCounter, savePath, currDoc){
var fileSearch = -1;
//Define the location of each draft folder
var internalFolder = new Folder(savePath + "/" + draftCounter);
//Look in each folder and create an array containing all of the information
var internalFileList = internalFolder.getFiles();
// Look at each array and sort the info out
for(var a=0; a<internalFileList.length; a++) {
//Exclude anything that is not a file
if(internalFileList[a] instanceof File) {
// convert each filename to string for editing
var fileName = internalFileList[a].toString();
//Searching the current document name and replacing spaces with %20
var currDocStripped = currDoc.replace(/ /g, '%20');
//Checking files until a result greater than 0 appears
if(fileSearch === -1){
//search for the current file name
fileSearch = fileName.search(currDocStripped);
}
}
}
//if the filesearch does not return a result:
if(fileSearch === -1){
fileNotFound = true;
//if it does return a result:
} else {
//Slice the number off the draft folder
draftCounter = draftCounter.slice(-3);
//convert the string into an integer
draftCounter = parseInt(Number(draftCounter));
//increment the number up
wipCounter++;
//terminate the main loop
fileNotFound = false;
}
}
//A resuable JPEG save script
function jpegFileSaver(doc, saveFile, quality){
//define the save options
var saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.quality = quality;
//save the files
doc.saveAs(saveFile, saveOptions, true);
}
Thanks in advance.
Additional credits to code author http://jamesmcdonald3d.com/
The issue is with searchDraftFolder(). When it finds the already saved Great Map_wip in draft001, fileNotFound is set to false and your loop on line 39 terminates. That's why wipCounter is stuck on 2: it increments ones and that's it.
Here I rewrote this function a little bit, trying to make it simpler: all necessary loops are inside the function and I think it's easier to understand.
p.s. there was also an issue at least on CC: app.documents.add() was showing interface. That's because you were using a full path as a new document name and you can't use \-symbol in it, so Photoshop was suggesting a different name and showing it. I added a separate variable for document name without a path (line 49) to use in .add()
main();
function main()
{
//Get file information
var doc = app.activeDocument;
var docName = doc.name;
var docPath = doc.path;
var wipCounter;
//Get the percentage to scale by
var scaleValue = prompt("Enter the WIP JPEG scale percentage", "100");
//Figure out the location of the WIP folder
var savePath = docPath.toString();
savePath = savePath.slice(0, -10);
savePath = savePath + "/4.WIP/";
var currDoc = docName.toString();
currDoc = currDoc.slice(0, -4);
//global variables are defined here
//Look at the WIP folder and run a search for anything containing the word "draft"
//Define the location of the WIP folder
var inWIPFolder = new Folder(savePath);
// !! modifications
wipCounter = searchDraftFolder(inWIPFolder, currDoc)
//Formatting the numbers
if (wipCounter < 10)
{
wipCounter = "00" + wipCounter.toString();
}
else if (wipCounter >= 10 && wipCounter < 100)
{
wipCounter = "0" + wipCounter.toString();
}
//Define the path of the draft folders
savePath = Folder(savePath + "/draft" + wipCounter);
//Check to see if the draft folders exists. If not, make one
if (!savePath.exists)
{
savePath.create();
}
//Define the WIP file name with the incremental counter
var wipFileName = currDoc + "_WIP" + wipCounter + ".jpg";
var wipFilePath = savePath + "/" + wipFileName;
//Resize the file
doc.selection.selectAll();
var blankLayer = doc.artLayers.add();
blankLayer.name = "blankLayer";
doc.selection.copy(true);
doc.layers.getByName("blankLayer").remove();
//Make new doc to paste into
app.preferences.rulerUnits = Units.PIXELS;
//arguments are: Width, Height, resolution, filename, colourspce, documentfill
app.documents.add(UnitValue(doc.width, "PX"), UnitValue(doc.height, "PX"), doc.resolution, wipFileName, NewDocumentMode.RGB, DocumentFill.TRANSPARENT, 1);
app.activeDocument.paste();
app.activeDocument.resizeImage(UnitValue(scaleValue, "PERCENT"), null, null, ResampleMethod.BICUBICSHARPER);
//Save a RGBJpeg
jpegFileSaver(app.activeDocument, new File(wipFilePath), 10);
//Close the new document down
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
//Deselect
doc.selection.deselect();
alert(currDoc + "_WIP" + wipCounter + " saved.");
}
// p is WIP path
// n is a name of the active doc without extension
function searchDraftFolder(p, n)
{
var fileList = p.getFiles(); // folders in wip folder
var counter = 1;
var drafts, fileName, i, k;
// for all the files found..
for (i = 0; i < fileList.length; i++)
{
//if a folder is found and its name has 'draft' in it
if (fileList[i] instanceof Folder && fileList[i].name.indexOf('draft') != -1)
{
//get files inside this draft folder
drafts = fileList[i].getFiles();
// for all files inside
for (k = 0; k < drafts.length; k++)
{
//'.name' gives us a URI-name, so replacing %20 with ' '. Probably should add more special symbols here if you use them
fileName = drafts[k].name.replace(/%20/g, ' ');
// if there's a file that starts with active doc name counter is incremented
if (fileName.indexOf(n) != -1)
{
counter++
}
}
}
}
return counter;
}
//A resuable JPEG save script
function jpegFileSaver(doc, saveFile, quality)
{
//define the save options
var saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.quality = quality;
//save the files
doc.saveAs(saveFile, saveOptions, true);
}
This Google Apps Script Project takes photos from a Google Drive folder and uses these photos to create a slideshow. Basically, it takes the file name as the student's name, the file as the picture to be inserted into the slideshow, and it also puts the school logo and Grad ${{Current Year}}. I want this script to be able to deal with thousands of photos if possible without exceeding the quota.
Is there a way to optimize this code so it only runs for 1 to 2 mins and be able to deal with 1000 or more photos.
function createPresentation() {
var year, school, name, fileName, colour, foreground, font, nameSize, titleSize, gradSize, schoolLogo, deck;
year = new Date().getFullYear().toString(); // Current Year
school = 'High School'; // School Name
name = "Class of " + year;
fileName = "Class of " + year + " - " + school; // Class Year
colour = "#C53023"; // School Colour
foreground = "#000000"; // Foreground Colour (Black)
font = "Roboto"; // Font
nameSize = 70; // Font size for names
titleSize = 80; // Font size for title
gradSize = 33; // Font size for Grad 20..
schoolLogo = '.../logo.jpg'; // School Logo
deck = SlidesApp.create(fileName); // Creates the presentation
title(deck, font, name, colour, school, foreground, titleSize );
createSlides(deck, schoolLogo, year, gradSize, font);
createStudents(deck);
}
function title(deck, font, name, colour, school, fcolour, fsize ){
var [title, subtitle] = deck.getSlides()[0].getPageElements();
// Class of ${Current Year}
title.asShape().getText().setText(name);
title.asShape().getText().getTextStyle().setBold(true).setForegroundColor(colour).setFontSize(fsize).setFontFamily(font);
// School Name
subtitle.asShape().getText().setText(school);
subtitle.asShape().getText().getTextStyle().setBold(true).setFontFamily(font).setForegroundColor(fcolour).setFontSize(33);
}
function countFiles() {
// Function to count the number of files in the folder
var files = DriveApp.getFoldersByName("Test").next().getFiles();
var count = 0;
while (files.hasNext()){
count++;
file = files.next();
}
return count;
}
function measureImage(){
}
function createSlides(deck, logoURL, year, fontSize, font) {
// Function to create slides
var numSlides = parseInt(countFiles()); // Number of files in Graduation folder
for (var i = 0; i < numSlides; i++) {
slide = deck.appendSlide(SlidesApp.PredefinedLayout.BLANK);
var logo = slide.insertImage(logoURL).setTop(322).setLeft(50).setHeight(60).setWidth(80);
var caption = 'GRAD' + " " + year;
var shape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX, 149, 324, 260, 90);
var textRange = shape.getText();
textRange.setText(caption).getTextStyle().setFontSize(fontSize).setFontFamily(font).setBold(true);
}
}
function createStudents(deck){
// Get names and pictures from file
var count = 1;
// Student Names
var folder = "Test" // Folder Name
var files = DriveApp.getFoldersByName(folder).next().getFiles(); // Get files from folder
while (files.hasNext()){
var file = files.next();
var slide = deck.getSlides()[count]
// Get and format students' name from file name.
var studentName = file.getName();
var studentf = studentName.split('.').slice(0, -1).join('.')
var fields = studentf.split('_');
var firstname = fields[1] ;
var lastname = fields[0];
// Place the name on the slide
var shape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX, 50, 80, 320, 120);
var textRange = shape.getText();
textRange.setText(firstname + '\n' + lastname).getTextStyle().setFontSize(60).setFontFamily('Roboto').setBold(false).setForegroundColor('#C53023');
var paragraphs = textRange.getParagraphs();
for (var i = 0; i < 2; i++) {
var paragraphStyle = paragraphs[i].getRange().getParagraphStyle();
paragraphStyle.setParagraphAlignment(SlidesApp.ParagraphAlignment.CENTER);
}
// Get the image and set its location.
var image = slide.insertImage(file.getAs('image/png'));
var imgWidth = image.getWidth();
var imgHeight = image.getHeight();
var pageWidth = deck.getPageWidth();
var pageHeight = deck.getPageHeight();
var newX = pageWidth/2. - imgWidth/2.;
var newY = pageHeight/2. - imgHeight/2.;
image.setLeft(newX+200).setTop(newY);
count++;
}
}
Every time the script runs, it gets timed out after ~366 seconds (~6.1 mins).
Can anyone help me write a script for illustrator CC2017 that Export files to web (legacy) as JPG then save the file and close after. I have 700 files each with 2 art boards and it would be painful to click file>Export>Save For Web(legacy) then right the file name and save the file then close.
Here is the script as per your requirement. I have just updated Script 1 to match your requirement. By default it assumes ruler is in Points and convert it into inches and use in the file name. You can add more check to handle other ruler units. This will have a-z if artboards are not more than 26 in case artboards are more than 26, it will show something else. Using ASCII code for this
var folder = Folder.selectDialog();
if (folder) {
var files = folder.getFiles("*.ai");
for (var i = 0; i < files.length; i++) {
var currentFile = files[i];
app.open(currentFile);
var activeDocument = app.activeDocument;
var jpegFolder = Folder(currentFile.path + "/JPG");
if (!jpegFolder.exists)
jpegFolder.create();
var codeStart = 97; // for a;
for (var j = 0; j < activeDocument.artboards.length; j++) {
var activeArtboard = activeDocument.artboards[j];
activeDocument.artboards.setActiveArtboardIndex(j);
var bounds = activeArtboard.artboardRect;
var left = bounds[0];
var top = bounds[1];
var right = bounds[2];
var bottom = bounds[3];
var width = right - left;
var height = top - bottom;
if (app.activeDocument.rulerUnits == RulerUnits.Points) { //Add more if for more conversions
width = width / 72;
height = height / 72;
}
var fileName = activeDocument.name.split('.')[0] + "-" + String.fromCharCode(codeStart) + "-" + width + "x" + height + ".jpg";
var destinationFile = File(jpegFolder + "/" + fileName);
var type = ExportType.JPEG;
var options = new ExportOptionsJPEG();
options.antiAliasing = true;
options.artBoardClipping = true;
options.optimization = true;
options.qualitySetting = 100; // Set Quality Setting
activeDocument.exportFile(destinationFile, type, options);
codeStart++;
}
activeDocument.close(SaveOptions.DONOTSAVECHANGES);
currentFile = null;
}
}
Here is the javascript code that will export all ai files present in the selected folder into a jpg. This code will ask you to select a folder. So select folder that will have 700 files
Script 1: Using JPEGQuality
var folder = Folder.selectDialog();
if (folder) {
var files = folder.getFiles("*.ai");
for (var i = 0; i < files.length; i++) {
var currentFile = files[i];
app.open(currentFile);
var activeDocument = app.activeDocument;
var jpegFolder = Folder(currentFile.path + "/JPG");
if (!jpegFolder.exists)
jpegFolder.create();
for (var j = 0; j < activeDocument.artboards.length; j++) {
var activeArtboard = activeDocument.artboards[0];
activeDocument.artboards.setActiveArtboardIndex(j);
var fileName = activeDocument.name.split('.')[0] + "Artboard" + (j + 1) + ".jpg";
var destinationFile = File(jpegFolder + "/" + fileName);
var type = ExportType.JPEG;
var options = new ExportOptionsJPEG();
options.antiAliasing = true;
options.artBoardClipping = true;
options.optimization = true;
options.qualitySetting = 100; // Set Quality Setting
activeDocument.exportFile(destinationFile, type, options);
}
activeDocument.close(SaveOptions.DONOTSAVECHANGES);
currentFile = null;
}
}
Since you have two artboards in each ai file. It will create two separate jpg for each artboard. You can change file name and folder location for jpg images as per requirement.
Script 2: By changing resolution
var folder = Folder.selectDialog();
if (folder) {
var files = folder.getFiles("*.ai");
for (var i = 0; i < files.length; i++) {
var currentFile = files[i];
app.open(currentFile);
var activeDocument = app.activeDocument;
var jpegFolder = Folder(currentFile.path + "/JPG");
if (!jpegFolder.exists)
jpegFolder.create();
var fileName = activeDocument.name.split('.')[0] + ".jpg";
var destinationFile = File(jpegFolder + "/" + fileName);
// Export Artboard where you can set resolution for an image. Set to 600 by default in code.
var opts = new ImageCaptureOptions();
opts.resolution = 600;
opts.antiAliasing = true;
opts.transparency = true;
try {
activeDocument.imageCapture(new File(destinationFile), activeDocument.geometricBounds, opts);
} catch (e) {
}
activeDocument.close(SaveOptions.DONOTSAVECHANGES);
currentFile = null;
}
}
For script 2, there will be only single file for one ai file, irrespective of the artboards.
SO you can run both script for your work and go ahead.
VBA example that uses one Excel-specific statement
Sub Export_All()
Dim fs As Object
Dim aiRef As Object
Dim docRef As Object
Dim jpegExportOptions As Object
Dim f As Object
Dim p As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set aiRef = CreateObject("Illustrator.Application")
Set jpegExportOptions = CreateObject("Illustrator.ExportOptionsJPEG")
' Specify all export options here
jpegExportOptions.AntiAliasing = False
jpegExportOptions.QualitySetting = 70
p = Application.ActiveWorkbook.Path ' Excel-specific. You may change it to whatever you like
For Each f In fs.GetFolder(p).Files
If LCase(Right(f.Name, 3) = ".ai") Then
Debug.Print f.Name
Set docRef = aiRef.Open(p + "\" + f.Name)
Call docRef.Export(p + "\" + f.Name + ".jpg", 1, jpegExportOptions)
Set docRef = Nothing
End If
Next
' Note that AI is still open and invisible
End Sub
I'm not a programmer, but trying to write a script for Photoshop. Below is something that I found, but it simply increments the files "1.png, 2.png, etc..." I'd like to name the exported files, "documentName_canvasWidth_canvasHeight_incrementedNumber.png"
function sfwPNG24(saveFile){
var pngOpts = new ExportOptionsSaveForWeb;
pngOpts.format = SaveDocumentType.PNG
pngOpts.PNG8 = false;
pngOpts.transparency = true;
pngOpts.interlaced = false;
pngOpts.quality = 100;
activeDocument.exportDocument(new File(saveFile),ExportType.SAVEFORWEB,pngOpts);
}
/*
Incrementing a number inside a text layer then Saving it in PNG
*/
var layer = activeDocument.layers[0];
if (layer.kind == 'LayerKind.TEXT') {
for (var i=1; i < 7; i++) {
layer.textItem.contents = i.toString();
sfwPNG24( 'filepathgoeshere'+ i +'.png');
};
};
Add these changes to the second part of the code:
var layer = activeDocument.layers[0];
// documentName_canvasWidth_canvasHeight_incrementedNumber.png
var srcDoc = app.activeDocument;
// get width and height
var W = srcDoc.width.value;
var H = srcDoc.height.value;
// get document name
var fn = srcDoc.name;
if (layer.kind == 'LayerKind.TEXT')
{
for (var i=1; i < 7; i++)
{
layer.textItem.contents = i.toString();
sfwPNG24( 'filepathgoeshere'+ W + "_" + H + "_" + i +'.png')
}
}
I have excel as an activeX object in javascript. I seem to be missing something with reards to how to interact with the object model from there. My watch window shows the value of the "Value" property of the range I am trying to pull data from as "undefined" when I try to assign "range.Value" to an array.
Unfortunately I am unable to update the outdated browsers on my machine at work so I cannot upload pictures.
My script:
function open_files(A, B, C)
{
var excel = new ActiveXObject("Excel.Application");
excel.Visible=true;
excel.DisplayAlerts = false;
var wbA = excel.Workbooks.Open(document.getElementById(A).value);
var wbB = excel.Workbooks.Open(document.getElementById(B).value);
var wbC = excel.Workbooks.Open(document.getElementById(C).value);
excel.EnableEvents = false;
excel.ScreenUpdating = false;
excel.Calculation = -4135 //xlCalculationManual enumeration;
var wb_collection = [wbA, wbB, wbC];
excel.Application.Run("'" + wbA.name + "'" + '!update_links');
var CLIN_list = [wbA.Sheets("Control Form").Range("B62:B141").value(1)]
for (i = 0; i = CLIN_list.length; i++)
{
if (CLIN_list(i) > 0)
{
var CLIN_list_count = i
}
}
var decrement_range_start = wbA.Sheets("Fee & Decrement Table").Range("AJ14")
//for (i = 0; i < 80; i++){
//Sheets("Fee & Decrement Table").Cells(decrement_range_start.column+i
// Model Setup for VBA
wbA.Sheets("CONTROL FORM").Activate
wbA.Sheets("CONTROL FORM").OLEObjects("TextBox21").Object.Text = wbB.fullname
wbA.Sheets("CONTROL FORM").OLEObjects("TextBox22").Object.Text = wbC.fullname
excel.Application.Run("'" + wbA.name + "'" + '!Run_JPO');
I found an answer on another forum. A Range cannot be assigned directly to a js array, it has to be converted. The line below works to fill my CLIN_list variable.
var CLIN_list = new VBArray(wbA.Sheets("Control Form").Range("B62:B141").value).toArray();