Photoshop: export layers to files adding group-name as prefix - photoshop-script

I need to save hundreds layers as jpg files from a given psd.
Leyers are grouped in several groups and every group's name should compare as the prefix in the jpg's files.
Group1
|
layer1
|
layer2
|
layer3
Group2
|
layer1
|
layer2
I need something like this:
Group1-layer1.jpg
Group1-layer2.jpg
Group1-layer3.jpg
Group2-layer1.jpg
Group2-layer2.jpg
I found many .jsx scripts that merge and export groups but can't find anything according to my needs. Does anyone know how to do that?
thank you
ema

Try this code.
#target photoshop
//$.level = 2;
/*
* Script by Loginoff Nick (nloginoff (at) gmail dot com)
* Script export layers to files adding group-name as prefix or create folders like a groups
* Function translite - replac a russian words to english.
* Photoshop CS5
* 04.02.2014
*
*/
var LONG_NAMES = 0; // Save Long Names - Folder_SubFolder_Layer or save only "Layer"
var CREATE_FOLDERS = 1; // Create Hierarchy Folders. Warning if this 0 and LONG_NAMES = 0, maybe recreate files.
var SEPARATOR = '_'; // Separator for file name
var PREFIX_FILE = '' + SEPARATOR; //
function main(){
if(!documents.length) return;
var doc = activeDocument;
var DocPath = activeDocument.path;
var DocName = translite(doc.name.replace(/\.psd/g,''));
var outFolder = new Folder(DocPath + "/" + DocName + "_layers");
if (!outFolder.exists) {
outFolder.create();
}
scanLayers(doc,outFolder,PREFIX_FILE + DocName);
function scanLayers(el, current_folder, prefix_name) {
for(var a=0;a<el.layers.length;a++) {
var lname = translite(el.layers[a].name);
var file_name = lname;
if ( LONG_NAMES ) {
file_name = prefix_name + SEPARATOR + lname;
}
saveLayer(el.layers[a], file_name, current_folder, false);
// recurstion
if ( el.layers[a].layers && el.layers[a].layers.length > 0 ) {
var new_folder = current_folder;
if ( CREATE_FOLDERS ) {
new_folder = current_folder + "/" + lname;
var destFolder = new Folder(new_folder);
if (!destFolder.exists) {
destFolder.create();
}
}
scanLayers(el.layers[a], new_folder, file_name);
}
}
}
function translite(str){
var arr={'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d', 'е':'e', 'ж':'g', 'з':'z', 'и':'i', 'й':'y', 'к':'k', 'л':'l', 'м':'m', 'н':'n', 'о':'o', 'п':'p', 'р':'r', 'с':'s', 'т':'t', 'у':'u', 'ф':'f', 'ы':'i', 'э':'e', 'А':'A', 'Б':'B', 'В':'V', 'Г':'G', 'Д':'D', 'Е':'E', 'Ж':'G', 'З':'Z', 'И':'I', 'Й':'Y', 'К':'K', 'Л':'L', 'М':'M', 'Н':'N', 'О':'O', 'П':'P', 'Р':'R', 'С':'S', 'Т':'T', 'У':'U', 'Ф':'F', 'Ы':'I', 'Э':'E', 'ё':'yo', 'х':'h', 'ц':'ts', 'ч':'ch', 'ш':'sh', 'щ':'shch', 'ъ':'', 'ь':'', 'ю':'yu', 'я':'ya', 'Ё':'YO', 'Х':'H', 'Ц':'TS', 'Ч':'CH', 'Ш':'SH', 'Щ':'SHCH', 'Ъ':'', 'Ь':'','Ю':'YU', 'Я':'YA'};
var replacer=function(a){return a in arr ? arr[a] : '';};
return str.replace(/[А-яёЁьЬ]/g,replacer).toLowerCase();
}
};
main();
function saveLayer(layer, lname, path, shouldMerge) {
activeDocument.activeLayer = layer;
dupLayers();
if (shouldMerge === undefined || shouldMerge === true) {
activeDocument.mergeVisibleLayers();
}
activeDocument.trim(TrimType.TRANSPARENT,true,true,true,true);
var saveFile= File(path +"/"+lname+'.png');
SavePNG(saveFile);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
};
function dupLayers() {
var desc143 = new ActionDescriptor();
var ref73 = new ActionReference();
ref73.putClass( charIDToTypeID('Dcmn') );
desc143.putReference( charIDToTypeID('null'), ref73 );
desc143.putString( charIDToTypeID('Nm '), activeDocument.activeLayer.name );
var ref74 = new ActionReference();
ref74.putEnumerated( charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
desc143.putReference( charIDToTypeID('Usng'), ref74 );
executeAction( charIDToTypeID('Mk '), desc143, DialogModes.NO );
};
function SavePNG(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);
};

Related

Is there a way to use fusion algorithms like STARFM in Google Earth Engine?

Landsat and MODIS products both have their advantages. Landsat with its high spatial resolution and MODIS with its high temporal resolution. I've read a lot about downloading the files and fuse them locally with algorithms like STARFM in Python for example. Is there a way to fuse both collections directly in Google Earth Engine to save computational time?
There is Google earth engine code in GitHub. The link is below:
https://github.com/MacGallagher/GEE_STARFM_FUSION
The code I copied is below:
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var l8 = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR"),
modis = ee.ImageCollection("MODIS/006/MOD09GQ"),
geometry4 = /* color: #d63000 */ee.Geometry.Polygon(
[[[-116.004638671875, 42.809506838324204],
[-115.59539794921875, 42.78129125156276],
[-115.499267578125, 43.004647127794435],
[-115.499267578125, 43.28920196020127],
[-116.00189208984375, 43.35114690203121],
[-116.19415283203125, 43.07691312608711]]]),
geometry = /* color: #98ff00 */ee.Geometry.Polygon(
[[[-115.93391418457031, 43.09346209534859],
[-115.80276489257812, 43.095718426590174],
[-115.80276489257812, 43.161366298103566],
[-115.9332275390625, 43.16086543618915]]]);
/***** End of imports. If edited, may not auto-convert in the playground. *****/
// based on script by Faye Peters, University of Louisville
// modified by Megan Gallagher, Boise State University
// for code inquiries, or adjustments please email megangallagher#u.boisestate.edu
// code exists for:
// landsat 5,7, and 8 NDVI merging with MODIS Terra daily
// MODIS Terra and Sentinel-2
// Landsat pre tier and modis daily terra - works with base R code
// Landsat 8 and Sentinel-2
////////////////////////////////////////Variables//////////////////////////////////////////////
// import Landsat 8 and MODIS daily terra surface reflectance 250m
var region = geometry; //region you want to export
var bounds = geometry4 //outer bounds of image to catch boundary effect, make larger than region
var date_begin = '2016-03-02' //start date of data collection, must be a landsat image date
var date_end ='2016-10-13' // end date of data collection, must be the day AFTER last landsat image
var csv_title = '2016_Dates_BOP' //title of csv output
var ls_title = '2016_landsat' // title of landsat tif file
var mod_title = '2016_mod' // title of modis tif file
/////////////////////////////////////////Code////////////////////////////////////////////////////////////////////////
var starfm = function(modis, l8){
//Preliminary filtering of MODIS and Landsat
var filt_mod = modis.filterDate(date_begin, date_end);
var filt_l8 = l8.filterDate(date_begin, date_end)
.filterBounds(bounds);
//add bounds to subset area
var subset_bounds = bounds.transform('EPSG:4326', 30).bounds().getInfo();
// get rid of bad pixels but keep metadata date information
var removeBadObservations = function(image){
var valid_data_mask = ee.Image(image).select('pixel_qa').bitwiseAnd(2).neq(0);
var numberBandsHaveData =
image.mask().reduce(ee.Reducer.sum());
var allOrNoBandsHaveData =
numberBandsHaveData.eq(0).or(numberBandsHaveData.gte(9));
var allBandsHaveData = allOrNoBandsHaveData;
//Make sure no band is just under zero
var allBandsGT = image.reduce(ee.Reducer.min()).gt(-0.001);
var result = ee.Image(image).mask(image.mask().and(valid_data_mask).and(allBandsHaveData).and(allBandsGT));
return result.copyProperties(ee.Image(image),['system:time_start']);
};
//NDVI functions for Landsat and MODIS
var getNDVI_mod = function(image){
return image
.addBands(image.normalizedDifference(['sur_refl_b02','sur_refl_b01']).multiply(10000).rename('NDVI'));};
var getNDVI_l8= function(image){
var ndvi = ee.Image(image).normalizedDifference(['B5','B4']);
return ndvi.copyProperties(ee.Image(image),['system:time_start']);
};
var filt2_l8= filt_l8.filterBounds(subset_bounds).aside(print).map(removeBadObservations).map(getNDVI_l8);
// update mask for different areas
var subset_mask = ee.Image().byte().paint(geometry4, "id").add(1);
var filtered_modis = filt_mod.filterBounds(subset_bounds).aside(print).map(getNDVI_mod);
// Pull out the date:
var extract_modis_date = function(row) {
var d = ee.Date(row.get('system:time_start'));
var d2 = ee.Date.fromYMD(d.get('year'), d.get('month'), d.get('day'));
var result = ee.Feature(null, {'date': d2});
result = result.set({'date': d2});
return result;
};
var getQABits = function(image, start, end, newName) {
//// Compute the bits we need to extract.
var pattern = 0;
for (var i = start; i <= end; i++) {
pattern += Math.pow(2, i);
}
//// Return a single band image of the extracted QA bits, giving the band a new name.
return image.select([0], [newName])
.bitwiseAnd(pattern)
.rightShift(start); };
print(filtered_modis);
filtered_modis = filtered_modis.map(function(image){
var quality = getQABits(image.select(2), 4, 5, 'QAMask');
quality = quality.eq(3).not();
return image.clip(subset_bounds).mask(image.mask().multiply(subset_mask).multiply(quality));
});
filtered_modis = filtered_modis.select('NDVI'); //Take only NDVI band
var modis_multiband = ee.Image(filtered_modis.filterDate(date_begin, date_end).iterate( function(x, modis_multiband) {
return ee.Image(modis_multiband).addBands(ee.Image(x));
}, filtered_modis.first()));
var dates_modis = filtered_modis.map(extract_modis_date);
print(dates_modis.getInfo());
var filt2_l8_ndvi = filt2_l8.map(function(image) {
return ee.Image(image)
.clip(subset_bounds)
.mask(ee.Image(image).mask().multiply(subset_mask));
});
//use this to choose the range of days, and check for overlap
var day_expand = 1;
var reduceLandsatNDVI = function(MODISdate) {
MODISdate = ee.Date(MODISdate.get('date'));
var ndvi_subset = ee.ImageCollection(filt2_l8_ndvi).filterDate( MODISdate,
MODISdate.advance(day_expand, 'day') );
ndvi_subset = ndvi_subset.map(function (image) {
var diff = MODISdate.difference(ee.Date(ee.Image(image).get('system:time_start')), 'day').abs();
return ee.Image(image).set('diff', diff);
});
ndvi_subset = ndvi_subset.sort('diff');
var ndvi_first = ndvi_subset.reduce('first');
var ndvi_mean = ndvi_subset.reduce('mean');
return ee.Algorithms.If(
ndvi_first.bandNames(),
ndvi_first.eq(0).multiply(ndvi_mean).add(ndvi_first),
ee.Image(0)
);
};
var extract_landsat_date = function(MODISdate) {
MODISdate = ee.Date(MODISdate.get('date'));
var ndvi_subset =
ee.ImageCollection(filt2_l8_ndvi).filterDate( MODISdate,
MODISdate.advance(day_expand, 'day') );
ndvi_subset = ndvi_subset.map(function (image) {
var diff = MODISdate.difference(ee.Date(ee.Image(image).get('system:time_start')), 'day').abs();
return ee.Image(image).set('diff', diff);
});
ndvi_subset = ndvi_subset.sort('diff');
var d = ndvi_subset.aggregate_first('system:time_start');
var count = ndvi_subset.aggregate_count('system:time_start');
d = ee.Algorithms.If(
ee.Number(count).gt(0),
ee.Date(d),
ee.Date('1971-01-01')
);
d = ee.Date(d);
var d2 = ee.Date.fromYMD(d.get('year'), d.get('month'),
d.get('day'));
var result = ee.Feature(null, {'LSdate': d2, 'MODISdate':
MODISdate, 'CountLSScenes': count});
result = result.set({'LSdate': d2, 'MODISdate': MODISdate,
'CountLSScenes': count});
return result;
};
var ls_collection = dates_modis.map(reduceLandsatNDVI);
print(ls_collection,'ls collection');
var dates_landsat = dates_modis.map(extract_landsat_date);
Export.table(dates_landsat, csv_title);
var ls_multiband = ls_collection.iterate( function(x,
ls_multiband)
{ return ee.Image(ls_multiband).addBands(ee.Image(x));
}, ls_collection.first());
ls_multiband = ee.Image(ls_multiband).multiply(10000).int16();
ls_multiband = ls_multiband.mask(ls_multiband.mask().multiply(ls_multiband.neq(0)));
//remove repeated first layer
var ls_multiband2=ee.Image(ls_multiband.slice(1))
var modis_multiband2=ee.Image(modis_multiband.slice(1))
Export.image.toDrive({
image: modis_multiband2,
description: mod_title,
crs:'EPSG:4326 ',
region:region,
scale:30
});
Export.image.toDrive({
image: ls_multiband2,
description: ls_title,
crs:'EPSG:4326',
region:region,
scale:30
});
return 'Done!'
}
var running = starfm(modis,l8)
print(running)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

I have a google script that creates QR codes and Barcode. the QR Codes show up twice. Once where its suppose to and then at the end of the document

The code below generates a label that has a QR Code and barcode. Currently I am trying to get both to work. They both show up in the label but when it does the QR code will be added in the correct spot but also will add extra qr codes on the last label generated. The two qr codes at the end are itemnum qr codes and they are not suppose to be there. It normally puts them ontop of each other i moved them so people could see. The barcodes generate just fine but they don't scan
TEST SCRIPT here is a link to test it.. This is a test script and not part of a business so its easy to do. Basically what needs done is click on My Custom Menu and select reset labels. Once the labels are created you can go to the labels tab and select a few labels with serial numbers then go back to the menu and select create labels for selected items.
//####################################### Create Zebra Label #########################
function createZebraLabel(monthlySheet, newSheetName) {
var parentFolder = DriveApp.getFolderById('1mUPLw1PSi-guH19uJPCPWmogkpdckLcW');
var createdoc = DocumentApp.create('Zebra Label').getId();
doc = DocumentApp.openById(createdoc);
var id = createdoc;
var docFile = DriveApp.getFileById(doc.getId());
var target = parentFolder;
var file1 = DriveApp.getFileById(id);
var mkfile1 = file1.makeCopy(newSheetName, target).getId();
doc = DocumentApp.openById(mkfile1);
docFile.setTrashed(true);
//325
var body = doc.getBody().setPageWidth(325).setPageHeight(180).setMarginTop(.2).setMarginBottom(.2);
// var body = doc.getBody().setPageWidth(144).setPageHeight(144).setMarginTop(.2).setMarginBottom(.2);
var sourceSpreadSheet = SpreadsheetApp.openById(monthlySheet);
var ss = sourceSpreadSheet.getSheetByName('Sheet1');
var startRow = 1; // First row of data to process
var numRows = 250; // Number of rows to process
var startColumn = 1; // A=1 B=2
var numColumns = 5; // Number of columns to process
var dataRange = ss.getRange(startRow, startColumn, numRows, numColumns);
var data = dataRange.getValues();
for (var i = 1; i < data.length; ++i) {
var row = data[i];
var actualrow = i;
var itemnum = row[0]; // A column
var desc = row[1]; // B column
var serial = row[2]; // D column
var bin = row[3]; // D column
var qty = row[4];
var styleLeft = {};
styleLeft[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
styleLeft[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleLeft[DocumentApp.Attribute.FONT_SIZE] = 14;
styleLeft[DocumentApp.Attribute.BOLD] = true;
var styleRight = {};
styleRight[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
styleRight[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleRight[DocumentApp.Attribute.FONT_SIZE] = 14;
styleRight[DocumentApp.Attribute.BOLD] = true;
var itemBarcode = {};
itemBarcode[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
itemBarcode[DocumentApp.Attribute.FONT_FAMILY] = 'Libre Barcode 39 Extended Text';
itemBarcode[DocumentApp.Attribute.FONT_SIZE] = 25;
itemBarcode[DocumentApp.Attribute.BOLD] = false;
var serialBarcode = {};
serialBarcode[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
serialBarcode[DocumentApp.Attribute.FONT_FAMILY] = 'Libre Barcode 39 Extended Text';
serialBarcode[DocumentApp.Attribute.FONT_SIZE] = 20;
serialBarcode[DocumentApp.Attribute.BOLD] = false;
var nospace = {};
nospace[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
nospace[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
nospace[DocumentApp.Attribute.FONT_SIZE] = 1;
nospace[DocumentApp.Attribute.BOLD] = true;
var text = body.editAsText();
var itemqrcode = UrlFetchApp.fetch('https://chart.googleapis.com/chart?chs=70x70&cht=qr&chl=' + itemnum);
var serialqrcode = UrlFetchApp.fetch('https://chart.googleapis.com/chart?chs=70x70&cht=qr&chl=' + serial);
if (itemnum != '') {
//#################### SERIAL ###################
if (serial != '') { // SERIAL NUMBER
body.appendParagraph('').setAttributes(nospace);
var paragraph = body.appendParagraph('Item Number: ' + itemnum).setAttributes(styleLeft);
paragraph.addPositionedImage(itemqrcode.getBlob()).setLayout(DocumentApp.PositionedLayout.WRAP_TEXT)
body.appendParagraph('*' + itemnum + '*').setAttributes(itemBarcode);
body.appendParagraph('\n\n').setAttributes(nospace).appendHorizontalRule();
//description
body.appendParagraph(desc).setAttributes(styleLeft);
body.appendParagraph('').setAttributes(nospace);
//serials
body.appendParagraph('').setAttributes(nospace).appendHorizontalRule();
var paragraph = body.appendParagraph('Serial Number: ' + serial).setAttributes(styleRight);
body.appendParagraph('*' + serial + '*').setAttributes(serialBarcode);
paragraph.addPositionedImage(serialqrcode.getBlob()).setLayout(DocumentApp.PositionedLayout.WRAP_TEXT)
body.appendParagraph('').setAttributes(nospace);
} else if (serial == '') { // NO SERIAL NUMBER
var styleCenter = {};
styleCenter[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
styleCenter[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleCenter[DocumentApp.Attribute.FONT_SIZE] = 18;
styleCenter[DocumentApp.Attribute.BOLD] = true;
var itemBarcode = {};
itemBarcode[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
itemBarcode[DocumentApp.Attribute.FONT_FAMILY] = 'Libre Barcode 39 Extended Text';
itemBarcode[DocumentApp.Attribute.FONT_SIZE] = 35;
itemBarcode[DocumentApp.Attribute.BOLD] = false;
var styleLocation = {};
styleLocation[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
styleLocation[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleLocation[DocumentApp.Attribute.FONT_SIZE] = 12;
styleLocation[DocumentApp.Attribute.BOLD] = true;
body.appendParagraph('').setAttributes(nospace);
var paragraph = body.appendParagraph('Item Number: ' + itemnum).setAttributes(styleLeft);
body.appendParagraph('*' + itemnum + '*').setAttributes(itemBarcode);
body.appendParagraph('\n').setAttributes(nospace).appendHorizontalRule();
//description
body.appendParagraph(desc).setAttributes(styleLeft);
body.appendParagraph('').setAttributes(nospace).appendHorizontalRule();
body.appendParagraph('Location: ' + bin + ' Qty: ' + qty).setAttributes(styleLocation);
body.appendParagraph('\n').setAttributes(nospace);
}
body.appendPageBreak();
}
}
var googledoc = doc.getUrl();
FinishedGoogleDoc(googledoc);
}
Below is my solution that does work.
/
/####################################### Create Zebra Label #########################
function createZebraLabel(monthlySheet,newSheetName){
var parentFolder=DriveApp.getFolderById('1mUPLw1PSi-guH19uJPCPWmogkpdckLcW');
var createdoc = DocumentApp.create('Zebra Label').getId();
doc = DocumentApp.openById(createdoc);
var id = createdoc;
var docFile = DriveApp.getFileById(doc.getId());
var target = parentFolder;
var file1 = DriveApp.getFileById(id);
var mkfile1 = file1.makeCopy(newSheetName, target).getId();
doc = DocumentApp.openById(mkfile1);
docFile.setTrashed(true);
//325
var body = doc.getBody().setPageWidth(325).setPageHeight(180).setMarginTop(.02).setMarginBottom(.02);
// var body = doc.getBody().setPageWidth(144).setPageHeight(200).setMarginTop(.01).setMarginBottom(.01);
var sourceSpreadSheet = SpreadsheetApp.openById(monthlySheet);
var ss = sourceSpreadSheet.getSheetByName('Sheet1');
var startRow = 1; // First row of data to process
var numRows = 250; // Number of rows to process
var startColumn = 1; // A=1 B=2
var numColumns = 5; // Number of columns to process
var dataRange = ss.getRange(startRow, startColumn, numRows, numColumns);
var data = dataRange.getValues();
for (var i = 1; i < data.length; ++i) {
var row = data[i];
var actualrow=i;
var itemnum = row[0]; // A column
var desc = row[1]; // B column
var serial = row[2]; // D column
var bin = row[3]; // D column
var qty =row[4];
if (itemnum != ''){
var styleITEMNUM = {};
styleITEMNUM[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
styleITEMNUM[DocumentApp.Attribute.VERTICAL_ALIGNMENT] =DocumentApp.VerticalAlignment.CENTER;
styleITEMNUM[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleITEMNUM[DocumentApp.Attribute.FONT_SIZE] = 14;
styleITEMNUM[DocumentApp.Attribute.BOLD] = true;
var styleDESC = {};
styleDESC[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
styleDESC[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleDESC[DocumentApp.Attribute.FONT_SIZE] = 10;
styleDESC[DocumentApp.Attribute.BOLD] = true;
var styleSERIAL = {};
styleSERIAL[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
styleSERIAL[DocumentApp.Attribute.VERTICAL_ALIGNMENT] =DocumentApp.VerticalAlignment.CENTER;
styleSERIAL[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleSERIAL[DocumentApp.Attribute.FONT_SIZE] = 12;
styleSERIAL[DocumentApp.Attribute.BOLD] = true;
var nospace = {};
nospace[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
nospace[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
nospace[DocumentApp.Attribute.FONT_SIZE] =-1;
nospace[DocumentApp.Attribute.BOLD] = true;
var text = body.editAsText();
var paraStyle = {};
paraStyle[DocumentApp.Attribute.PADDING_BOTTOM] = 0;
paraStyle[DocumentApp.Attribute.PADDING_TOP] = 0;
paraStyle[DocumentApp.Attribute.MARGIN_TOP] = 0;
paraStyle[DocumentApp.Attribute.SPACING_BEFORE] = 0;
paraStyle[DocumentApp.Attribute.SPACING_AFTER] = 0;
paraStyle[DocumentApp.Attribute.LINE_SPACING] = 0;
var itemqrcode = UrlFetchApp.fetch('https://chart.googleapis.com/chart?chs=80x80&cht=qr&chl='+itemnum);
var serialqrcode = UrlFetchApp.fetch('https://chart.googleapis.com/chart?chs=80x80&cht=qr&chl='+serial);
//#################### ITEM WITH SERIAL NUMBER ###################
if (itemnum != '' && serial != ''){ // SERIAL NUMBE
body.appendParagraph('').setAttributes(nospace);
var table = body.appendTable().setBorderWidth(0).setAttributes(paraStyle);
var tr = table.appendTableRow().setAttributes(paraStyle);
var td = tr.appendTableCell('').setWidth(80).setPaddingTop(0).setPaddingBottom(0).appendImage(itemqrcode.getBlob()).setAttributes(paraStyle);
var td = tr.appendTableCell('Item Number\n' +itemnum).setPaddingTop(0).setPaddingBottom(0).setAttributes(styleITEMNUM);
body.appendHorizontalRule().setAttributes(nospace);
body.appendParagraph(desc).setAttributes(styleDESC);
body.appendParagraph('').setAttributes(nospace).appendHorizontalRule().setAttributes(nospace);
body.appendParagraph('').setAttributes(nospace);
var table = body.appendTable().setBorderWidth(0).setAttributes(paraStyle);
var tr = table.appendTableRow().setAttributes(paraStyle);
var td = tr.appendTableCell('').setWidth(80).setPaddingTop(0).setPaddingBottom(0).appendImage(serialqrcode.getBlob()).setHeight(80);
var td = tr.appendTableCell('Serial Number\n ' +serial).setPaddingTop(0).setPaddingBottom(0).setAttributes(styleSERIAL);
}
else if (itemnum != '' && serial == ''){ // NO SERIAL NUMBER
var styleLocation = {};
styleLocation[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
styleLocation[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleLocation[DocumentApp.Attribute.FONT_SIZE] =12;
styleLocation[DocumentApp.Attribute.BOLD] = true;
body.appendParagraph('').setAttributes(nospace);
var table = body.appendTable().setBorderWidth(0).setAttributes(paraStyle);
var tr = table.appendTableRow().setAttributes(paraStyle);
var td = tr.appendTableCell('').setWidth(80).setPaddingTop(0).setPaddingBottom(0).appendImage(itemqrcode.getBlob()).setAttributes(paraStyle);
var td=tr.appendTableCell('Item Number\n' +itemnum).setAttributes(styleITEMNUM);
body.appendParagraph('\n').setAttributes(nospace).appendHorizontalRule();
body.appendParagraph(desc).setAttributes(styleDESC);
body.appendParagraph('\n').setAttributes(nospace).appendHorizontalRule();
body.appendParagraph('').setAttributes(nospace);
var table = body.appendTable().setBorderWidth(0).setAttributes(paraStyle);
var tr = table.appendTableRow().setAttributes(paraStyle);
var td=tr.appendTableCell('Location:'+bin).setWidth(200).setPaddingTop(0).setPaddingBottom(0).setAttributes(styleLocation);
var td=tr.appendTableCell('Qty: ' +qty).setAttributes(styleLocation);
}
body.appendPageBreak();
}
}
var googledoc = doc.getUrl();
FinishedGoogleDoc(googledoc);
}

Icon calendar generator

Are there any calendar Photoshop/illustrator scripts which can automatically generate a date number similar to this calendar icon image?
I need similar icon with date (1,2,3..31) and name of every month but in .png format. I cannot use html/css3 and jquery to create icon.
Thank you for answers and help
Yes, it's possible. I like a challenge:)
First with the template image open
Second create a folder folder C:\temp\calendar (or change the destination path in the script)
Run the script below and it'll generate dates as defined with sdate & eDate (start & end date) - currently November, 30 to December 01
// Load in background image before running script
// call the source document
var srcDoc = app.activeDocument;
var sDate = new Date("November, 30, 2016 00:00:00");
var eDate = new Date("January, 01, 2017 00:00:00");
var myPath = "c:\\temp\\calendar"
printDate(sDate, eDate, myPath, srcDoc);
//-----------------------------
function printDate(start, end, apath, sauce)
{
if (start == undefined) return;
if (end == undefined) return;
// set long month names
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
str = "";
// main loop here
while(start <= end)
{
// Display the month, day, and year.
// getMonth() returns a 0-based number.
var monthNum = start.getMonth()+1;
var month = monthNames[monthNum-1].toUpperCase();
var day = start.getDate();
var year = start.getFullYear();
// alert(month + " " + day + " " + year);
// num padding
if (monthNum < 10) monthNum = "0" + monthNum;
if (day < 10) day = "0" + day;
var theDate = "cal_" + monthNum + "_" + day + "_" + year;
duplicateIt(theDate);
var day = start.getDate();
str = (day);
var newDate = start.setDate(start.getDate() + 1);
// fontface, size, R,G,B, text, X, Y
// print bigmonth
createText("Arial-BoldMT", 38.0,255, 255, 255, month, 582, 460);
// print big day
createText("Arial-BoldMT", 176.0, 0, 0, 0, day, 582, 1144);
var f = apath + "\\" + theDate + ".png";
// alert(f)
saveAsPNG(f, 10);
// close that saved png
app.activeDocument.close();
// get the original source doc
app.activeDocument = sauce;
// reset start
start = new Date(newDate);
}
}
// function DUPLICATE IT (str)
// --------------------------------------------------------
function duplicateIt(str)
{
// duplicate image into new document
if (arguments.length == 0) str = "temp";
var id428 = charIDToTypeID( "Dplc" );
var desc92 = new ActionDescriptor();
var id429 = charIDToTypeID( "null" );
var ref27 = new ActionReference();
var id430 = charIDToTypeID( "Dcmn" );
var id431 = charIDToTypeID( "Ordn" );
var id432 = charIDToTypeID( "Frst" );
ref27.putEnumerated( id430, id431, id432 );
desc92.putReference( id429, ref27 );
var id433 = charIDToTypeID( "Nm " );
desc92.putString( id433, str ); // name
executeAction( id428, desc92, DialogModes.NO );
}
// function SAVE JPEG(file name & path)
// --------------------------------------------------------
function saveAsPNG(afilePath)
{
// flatten it
activeDocument.flatten();
// save as a png
var pngFile = new File(afilePath);
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.embedColorProfile = true;
pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
pngSaveOptions.matte = MatteType.NONE; pngSaveOptions.quality = 1;
activeDocument.saveAs(pngFile, pngSaveOptions, false, Extension.LOWERCASE);
}
// function CREATE TEXT(typeface, size, R, G, B, content, Xpos, Ypos, justify)
// --------------------------------------------------------
function createText(fface, size, colR, colG, colB, content, X, Y)
{
// Add a new layer in the new document
var artLayerRef = app.activeDocument.artLayers.add()
// Specify that the layer is a text layer
artLayerRef.kind = LayerKind.TEXT;
artLayerRef.name = content;
//This section defines the color of the text
textColor = new SolidColor();
textColor.rgb.red = colR;
textColor.rgb.green = colG;
textColor.rgb.blue = colB;
//Get a reference to the text item so
// that we can add the text and format it a bit
textItemRef = artLayerRef.textItem
textItemRef.font = fface;
textItemRef.contents = content;
textItemRef.color = textColor;
textItemRef.size = size;
//pixels from the left, pixels from the top
textItemRef.position = new Array(X, Y)
just = Justification.CENTER;
activeDocument.activeLayer.textItem.justification = just;
}
It's save them as .PNG files named after the date.

How do I fix charset problems in .gs script?

I have a problem with charsets.
I parsed a csv file in google-app-engine and I'm posting to an uiapp table.
But I checked special characters like áéíóú and those are not well displayed (?square symbol).
When I was setting up my code I played writing the string imported to a google docs document and it worked the same.
some advice please?
I search for:
a global charset definition to the code. or
string var transformation that makes the chars appear like I want to. (avoiding html &number definitions.
Is this related to the blob object?
The thing is important i come from spain and we need such characters.
app that get's a csv ';' delimited file and shows it's content
I post all my code, it's barely as the tutorial that is given.
function arreglaUrl(cadena){
var texto = cadena[cadena.length - 2]
if (texto == ''){
cadena[cadena.length - 2] = 'Sin enlace';
}
else{
cadena[cadena.length - 2] = '<center>Link.</center>' ;
};
}
function parsedCSV(){
var listaArchivos = DocsList.getFolderById('XXXXX').getFiles()
for (var i = 0; i < listaArchivos.length; i++) {
if (listaArchivos[i].getName() == 'baul.csv'){
var origen = listaArchivos[i];
};
}
var texto = origen.getContentAsString();
var arra = Utilities.parseCsv(texto,";");
return(arra);
}
function doGet() {
var datos = parsedCSV()
var baul = Charts.newDataTable()
for (i = 0; i < datos[0].length; i++){
baul.addColumn(Charts.ColumnType.STRING, datos[0][i])
}
for (i = 1; i < datos.length; i++){
arreglaUrl(datos[i]) // this only makes some html i need to post some links
baul.addRow(datos[i])
}
baul.build();
var sectorFilter = Charts.newCategoryFilter()
.setFilterColumnLabel("sector")
.build();
var tipoFilter = Charts.newCategoryFilter()
.setFilterColumnLabel("tipo")
.build();
var searchFilter = Charts.newStringFilter()
.setFilterColumnLabel("Titulo")
.build();
var searchDesc = Charts.newStringFilter()
.setFilterColumnLabel("descripcion")
.build();
var tableChart = Charts.newTableChart().setOption('allowHtml', true).setDimensions(0,0)
.build();
var dashboard = Charts.newDashboardPanel()
.setDataTable(baul)
.bind([sectorFilter, tipoFilter, searchFilter, searchDesc], [tableChart])
.build();
var uiApp = UiApp.createApplication().setTitle('Baul de Recursos');
var anchoTotal = '100%';
dashboard.add(uiApp.createVerticalPanel()
.add(uiApp.createHorizontalPanel()
.add(sectorFilter)
.add(tipoFilter)
.setSpacing(15)
)
.add(uiApp.createHorizontalPanel()
.add(searchFilter)
.add(searchDesc)
.setSpacing(15)
)
.add(uiApp.createHorizontalPanel()
.add(tableChart).setBorderWidth(1).setHorizontalAlignment(UiApp.HorizontalAlignment.CENTER).setWidth(anchoTotal)
)
);
uiApp.add(dashboard);
return uiApp;
}
I found it, we need to get the content of the file first with a Blob object.
This function is the one I use to parse some csv info into an array:
function parsedCSV(){
//searching the file. This gets only one file in var origen
var listaArchivos = DocsList.getFolderById('XXXXXXX').getFiles()
for (var i = 0; i < listaArchivos.length; i++) {
if (listaArchivos[i].getName() == 'baul.csv'){
var origen = listaArchivos[i];
};
}
// HERE IS THE GOOD DEFINITION OF CHAR:
var texto2= origen.getBlob().getDataAsString('ISO-8859-1');
// I put all the corrected text in an array
var arra = Utilities.parseCsv(texto2,";");
return(arra);
}
This is the solved thing: https://script.google.com/macros/s/AKfycbyHa-bLWBHBr3qifbvzxecqGgGUYX8mhyo-TKoyfGvy/exec
The trick:
var textVariableName = fileObjectVariableName.getBlob().getDataAsString('ISO-8859-1');

MVC3 uploadify uploading images to folders

I am using uploadify for uploading multiple images with progress in ASP.NET MVC3 and I want to upload lets say from url Gallery/Upload/2 to folder with name 2 and Gallery/Upload/3 to folder 3 and so on. I just don´t know how. For get working uploading I used this sample and modified sample upload script to this:
public string Upload(HttpPostedFileBase fileData)
{
var id = 2;
var fotka = new Photo();
fotka.GalleryId = id;
fotka.Description = fileData.FileName;
fotka.Name = fileData.FileName;
db.Photos.Add(fotka);
db.SaveChanges();
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileData.FileName);
var fileName = Path.GetFileName(fileData.FileName);
string path = Server.MapPath("~/Fotky/") + id.ToString() + "\\" + fileNameWithoutExtension;
// var path = Path.Combine(Server.MapPath("~/Fotky/"), galleryId.ToString(), "/", fileNameWithoutExtension);
using (var input = new Bitmap(fileData.InputStream))
{
int width;
int height;
if (input.Width > input.Height)
{
width = 128;
height = 128 * input.Height / input.Width;
}
else
{
height = 128;
width = 128 * input.Width / input.Height;
}
using (var thumb = new Bitmap(width, height))
using (var graphic = Graphics.FromImage(thumb))
{
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphic.DrawImage(input, 0, 0, width, height);
System.IO.Directory.CreateDirectory(Server.MapPath("~/Fotky/") + id.ToString());
using (var output = System.IO.File.Create(path + "_small" + Path.GetExtension(fileName)))
{
thumb.Save(output, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
fileData.SaveAs(path + Path.GetExtension(fileName));
return "ok";
}
as you can see I am using id as 2 as default, but I want to get it from parameters, is it posible? And how? Thank you
No one knows answer? It´s really important for me
You could have your controller action take the id as action argument:
public string Upload(HttpPostedFileBase fileData, string id)
{
...
}
and then pass this id when configuring your plugin:
$("#fileuploader").fileUpload({
'uploader': '#Url.Content("~/Scripts/uploader.swf")',
'cancelImg': '#Url.Content("~/Images/cancel.png")',
'buttonText': 'Select Image',
'script': '#Url.Action("Upload", "Home", new { id = "2" })',
'folder': '#Url.Content("~/uploads")',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'multi': true,
'auto': true
});

Resources