As I understand it you have a photoshop file. The background is on the bottom of the stack. The next layer, let's call it layer 1, and then layer 2 etc. Layers 1 & 2 need to be merged and exported. Then layers 1,2 & 3 need to merged and exported. You didn't mention if the background need to be merged with them. Anyway, I'm working on the assumption that the layers need to be merged with the background - it's easy to change, if that is not the case. Here's a script that will do want you want:
app.preferences.rulerUnits = Units.PIXELS;
// call the source document
var srcDoc = app.activeDocument;
fileName = app.activeDocument.name;
var myDocName = fileName.substring(0,fileName.length -4)
var numOfLayers = srcDoc.layers.length;
hideEverything(srcDoc)
processLayers (srcDoc)
function processLayers (sourceDocument)
{
for (var i = numOfLayers -1; i >= 0 ; i--)
{
srcDoc.activeLayer = srcDoc.artLayers[i];
thisLayer = srcDoc.artLayers[i].name;
// duplicate the document
var id17396 = charIDToTypeID( "Dplc" );
var desc3299 = new ActionDescriptor();
var id17397 = charIDToTypeID( "null" );
var ref2177 = new ActionReference();
var id17398 = charIDToTypeID( "Dcmn" );
var id17399 = charIDToTypeID( "Ordn" );
var id17400 = charIDToTypeID( "Frst" );
ref2177.putEnumerated( id17398, id17399, id17400 );
desc3299.putReference( id17397, ref2177 );
var id17401 = charIDToTypeID( "Nm " );
desc3299.putString( id17401, thisLayer ); //change the name of the document
executeAction( id17396, desc3299, DialogModes.NO );
// Flatten the image
app.activeDocument.flatten();
// Set myFilePath and fileName to source path
myFilePath = srcDoc.path + '/' + app.activeDocument.name +'.png';
try
{
// save out the image
var pngFile = new File(myFilePath);
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.embedColorProfile = true;
pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
pngSaveOptions.matte = MatteType.NONE; pngSaveOptions.quality = 1;
activeDocument.saveAs(pngFile, pngSaveOptions, false, Extension.LOWERCASE);
}
catch(e)
{
alert(e)
}
// close that saved png
app.activeDocument.close()
// select the document that's been open the longest
app.activeDocument = srcDoc;
}
}
function hideEverything(sourceDocument)
{
for (var i = numOfLayers -2; i >= 0 ; i--) // don't include background
{
srcDoc.artLayers[i].visible = false;
}
}