• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

InDesign: Script for exporting layers to jpg

Community Beginner ,
Dec 07, 2021 Dec 07, 2021

Copy link to clipboard

Copied

Hello

 

I'm looking for a Script that is capable to export my layers in a .indd file to jpgs in a Folder which I can choose. Also the Script need to name the exportet jpg's as the layer is named in the inDesign file.

 

Anyone an Idea how to makte this happen?

 

Thanks in advance!

TOPICS
Import and export , Scripting

Views

957

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 2 Correct answers

Community Expert , Dec 09, 2021 Dec 09, 2021

Yes you can export a selection. Selection is an array, so if the selection is more than one object you would have to handle how to group the pageitems. It could get complicated if the page items are on different layers. By default a page item’s name returns as nothing unless it has been named in the Layers panel, but the name could also be scripted. Something like this, which exports to the desktop:

 

 

 

app.jpegExportPreferences.properties = {
    antiAlias: true,
    embedColorProfile: true,
...

Votes

Translate

Translate
Community Beginner , Dec 10, 2021 Dec 10, 2021

@rob day 

You're the man! With a few changes and your Script, it works!

 

For everyone wondering how to do it, this is my take, bases on @rob day 's soulution:

 

app.jpegExportPreferences.properties = {
	antiAlias: true,
	embedColorProfile: true,
	exportResolution: 300,
	jpegColorSpace: JpegColorSpaceEnum.RGB,
	jpegQuality: JPEGOptionsQuality.maximum,
	simulateOverprint: false,
}

	var myFolder = Folder.selectDialog ("Select location to export the Jpeg files.");
	if (myFolder != null) {
		var mySelec
...

Votes

Translate

Translate
Advisor ,
Dec 08, 2021 Dec 08, 2021

Copy link to clipboard

Copied

hello @OPTEN 

 

The PageExporterUtility script will do what you're looking for...

https://github.com/paulhennell/InDesign-Page-Export-Utility/blob/master/PageExporterUtility5.0.1.jsx

Screen Shot 2021-12-08 at 4.40.38 AM.png

Regards,

Mike

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Dec 08, 2021 Dec 08, 2021

Copy link to clipboard

Copied

Hi Mike, 

 

Thanks for your fast reply. I've already tried to use that Script to change it how I needed it to work but couldn't finish it. Im Working on a new one.

I'll try your suggestion under this entry right now!

 

Hero!

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Advisor ,
Dec 08, 2021 Dec 08, 2021

Copy link to clipboard

Copied

Hello @OPTEN,

 

The below code is a bit more simplified.... I included the page # in the output name just to account for multi page documents, you can modify the code as needed.

 

var doc = app.activeDocument;

var myFolder = Folder.selectDialog ("Select location to export the Jpeg files.");
if (myFolder != null){ 
}else{
exit();
}

for(var p = 0; p < doc.pages.length; p++) {
var myPageName = doc.pages[p].name;

function myGetVisibleLayers(){
 var myVisibleLayers = new Array;
  for (var i = 0; i < doc.layers.length; i++){
   if (doc.layers[i].visible == true) {   
    myVisibleLayers.push(doc.layers[i].index);
      }
   }
      return myVisibleLayers;
  }

  var myVisibleLayers = myGetVisibleLayers();
      
  doc.layers.everyItem().visible = false;

  for (var i = 0; i < doc.layers.length; i++) {

  var my_layer = doc.layers[i].name;

  doc.layers[i].visible = true;

// Set JPEG export preferences 
app.jpegExportPreferences.properties = {
    antiAlias: true,
    embedColorProfile: true,
    exportResolution: 150,
    // exportingSpread: true, // Uncomment if spreads
    jpegColorSpace: JpegColorSpaceEnum.rgb,
    jpegExportRange: ExportRangeOrAllPages.exportRange,
    jpegQuality: JPEGOptionsQuality.maximum,
    jpegRenderingStyle: JPEGOptionsFormat.PROGRESSIVE_ENCODING,
    useDocumentBleeds: false,
    simulateOverprint: false,
    pageString: myPageName,
  }

 doc.exportFile(ExportFormat.jpg,File(myFolder + "/" + my_layer + "_pg" + myPageName + ".jpg"),false);

  doc.layers[i].visible = false;
}
  doc.layers.everyItem().visible = false;

  for (var i = 0; i < myVisibleLayers.length; i++){  
    var myLayers = myVisibleLayers[i];
    doc.layers[myLayers].visible =  true; 
    }
}
 alert("Done Exporting Layers to Jpeg's!");

 

 

Regards,

Mike

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Dec 08, 2021 Dec 08, 2021

Copy link to clipboard

Copied

This Works

 

Sadly the size of the Layer is to big. The whole site gets exportet to a jpg, but not only the LAyer it self. The size should be as the Layer size:

How it i s with this script:

08-123456_pg1.jpg

How it should be:

OPTEN_0-1638959983006.jpeg

 

I have a Script which exports the selected layers, but if i select more than one layer they're grouped an are exported as one jpg. Also the layer name doesn't work:

 

Main();

function Main() {
	// Check to see whether any InDesign documents are open.
	// If no documents are open, display an error message.
	if (app.documents.length > 0) {
		var myDoc = app.activeDocument;
		// Set the measurement system to points and the origin to page
		userHoriz = myDoc.viewPreferences.horizontalMeasurementUnits;
		userVert = myDoc.viewPreferences.verticalMeasurementUnits;
		userOrigin = myDoc.viewPreferences.rulerOrigin;
		myDoc.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;
		myDoc.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
		myDoc.viewPreferences.rulerOrigin = RulerOrigin.PAGE_ORIGIN;
		myDoc.zeroPoint = [0,0];
		// Prompt the user where to save the file
		var myFilePath = File.saveDialog("Choose a name and location for the file.");
		if (myFilePath) { // User did not click Cancel
			var myString = myFilePath.toString();
			var myLastSlash = myString.lastIndexOf("/");
			var myPath = myString.slice(0,myLastSlash+1);
			var myLastPeriod = myString.lastIndexOf(".");
			if (myLastPeriod == -1) {
				var myFileName = myString.slice(myLastSlash+1);
			}
			else {
				var myFileName = myString.slice(myLastSlash+1,myLastPeriod);
			}
			var myResultsArray = new Array;
			var myResultsArray = myInput();
			if (myResultsArray) { // User did not click Cancel
				// Gather the settings that are common to all exports
				var myWidth = myResultsArray[0];
				var myHeight = myResultsArray[1];
				switch(myResultsArray[2]) { // Quality
					case "Maximum":
						app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.MAXIMUM;
					break;
					case "High":
						app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.HIGH;
					break;
					case "Medium":
						app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.MEDIUM;
					break;
					case "Low":
						app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.LOW;
					break;
					default:
					break;
				}
				switch(myResultsArray[3]) { // Format method
					case "Progressive":
						app.jpegExportPreferences.jpegRenderingStyle = JPEGOptionsFormat.PROGRESSIVE_ENCODING;
					break;
					case "Baseline":
						app.jpegExportPreferences.jpegRenderingStyle = JPEGOptionsFormat.BASELINE_ENCODING;
					break;
					default:
					break;
				}
				switch(myResultsArray[4]) { // Colorspace
					case "RGB":
						app.jpegExportPreferences.jpegColorSpace = JpegColorSpaceEnum.RGB;
					break;
					case "CMYK":
						app.jpegExportPreferences.jpegColorSpace = JpegColorSpaceEnum.CMYK;
					break;
					case "Gray":
						app.jpegExportPreferences.jpegColorSpace = JpegColorSpaceEnum.GRAY;
					break;
					default:
					break;
				}
				app.jpegExportPreferences.embedColorProfile = myResultsArray[5]; // Color profile
				app.jpegExportPreferences.antiAlias = myResultsArray[6]; // Anti alias
				app.jpegExportPreferences.simulateOverprint = myResultsArray[7]; // Simulate overprint
				var mySelection = app.selection;
				if (mySelection.length > 0) { // At least 1 object is selected
					if (mySelection.length > 1) { // Multiple objects are selected
						var myObject = app.activeWindow.activePage.groups.add(app.selection);
						var myGroup = true;
					}
					else { // Only 1 object is selected
						var myObject = app.selection[0];
					}
					var myCurrentWidth = myObject.visibleBounds[3]-myObject.visibleBounds[1];
					var myCurrentHeight = myObject.visibleBounds[2]-myObject.visibleBounds[0];
					if (myWidth > 0) {
						// Calculate the scale percentage
						var myResizePercentage = myWidth/myCurrentWidth;
						var myExportRes = myResizePercentage * 72;	
					}
					else {
						// Calculate the scale percentage
						var myResizePercentage = myHeight/myCurrentHeight;
						var myExportRes = myResizePercentage * 72;
					}
					app.jpegExportPreferences.exportResolution = myExportRes;			
					myObject.exportFile(ExportFormat.JPG, File(myPath+myFileName+".jpg"), false);
					// undo the grouping
					if (myGroup) {
						myDoc.undo();
					}
				}
				else {
					alert("Nothing is selected. Please make a selection and try again.");
				}
			}
		}
		// Return the measurement system and origin to the way it was
		myDoc.viewPreferences.horizontalMeasurementUnits = userHoriz;
		myDoc.viewPreferences.verticalMeasurementUnits = userVert;
		myDoc.viewPreferences.rulerOrigin = userOrigin;
	}
	else {
		// No documents are open, so display an error message.
		alert("No InDesign documents are open. Please open a document and try again.")
	}
}

// Prompt the user for JPG export values
function myInput() {
	var myWindow = new Window("dialog", "Export to JPG - selection");
		myWindow.preferredSize = [372,418];
		myWindow.alignChildren = "right";
		var mySizePanel = myWindow.add("panel", undefined, "Enter the desired export size in pixels");
			mySizePanel.alignChildren = "left";
			mySizePanel.margins = 20;
			mySizePanel.preferredSize = [340,75];
			var mySizeGroup = mySizePanel.add("group", undefined);			
				mySizeGroup.add("statictext", undefined, "Width:");
				var myWidthField = mySizeGroup.add("edittext", undefined, ""); // width
					myWidthField.characters = 6;
					myWidthField.active = true;
				mySizeGroup.add("statictext", undefined, "\u00A0\u00A0\u00A0OR\u00A0\u00A0\u00A0");
				mySizeGroup.add("statictext", undefined, "Height:");
				var myHeightField = mySizeGroup.add("edittext", undefined, ""); // height
					myHeightField.characters = 6;					
		var myImagePanel = myWindow.add("panel", undefined, "Image");
			myImagePanel.orientation = "column";
			myImagePanel.alignChildren = "right";
			myImagePanel.margins = 20;
			myImagePanel.preferredSize = [340,106];
			var myQualityGroup = myImagePanel.add("group", undefined);
				myQualityGroup.orientation = "row";
				myQualityGroup.add("statictext", undefined, "Quality:");
				var myQualityField = myQualityGroup.add("dropdownlist", undefined, ["Maximum", "High", "Medium", "Low"]); // quality
					myQualityField.selection = 2;
					myQualityField.preferredSize = [200,21];
			var myFormatMethodGroup = myImagePanel.add("group", undefined);
				myFormatMethodGroup.orientation = "row";
				myFormatMethodGroup.add("statictext", undefined, "Format Method:");
				var myFormatMethodField = myFormatMethodGroup.add("dropdownlist", undefined, ["Progressive", "Baseline"]); // format
					myFormatMethodField.selection = 1;
					myFormatMethodField.preferredSize = [200,21];
			var myColorSpaceGroup = myImagePanel.add("group", undefined);
				myColorSpaceGroup.orientation = "row";
				myColorSpaceGroup.add("statictext", undefined, "Color Space:");
				var myColorSpaceField = myColorSpaceGroup.add("dropdownlist", undefined, ["RGB", "CMYK", "Gray"]); // color space
					myColorSpaceField.selection = 0;
					myColorSpaceField.preferredSize = [200,21];
		var myOptionsPanel = myWindow.add("panel", undefined, "Options");
			myOptionsPanel.orientation = "column";
			myOptionsPanel.alignChildren = "left";
			myOptionsPanel.margins = 20;
			myOptionsPanel.preferredSize = [340,127];
			var myColorProfileField = myOptionsPanel.add("checkbox", undefined, "\u00A0Embed Color Profile"); // color profile
				myColorProfileField.value = false;
			var myAliasField = myOptionsPanel.add("checkbox", undefined, "\u00A0Anti-alias"); // anti-alias
				myAliasField.value = true;
			var myOverprintField = myOptionsPanel.add("checkbox", undefined, "\u00A0Simulate Overprint"); // overprint
		var myButtonGroup = myWindow.add ("group");
			var myCancelBtn = myButtonGroup.add ("button", undefined, "Cancel");
			var myExportBtn = myButtonGroup.add ("button", undefined, "Export", {name:"ok"});
		myExportBtn.onClick = function() { // User clicked the OK button
			if (((myWidthField.text == "") && (myHeightField.text == "")) ||
				((myWidthField.text != "") && (myHeightField.text != ""))) {
				alert("Please enter an export width OR height in pixels"); // User left both width and height blank, or entered both a width and height
			}
			else {
				if (isNaN(myWidthField.text) || isNaN(myHeightField.text)) {
					alert ("Only numbers are allowed in the Width and Height fields"); // User entered a non-number in the width or height fields
				}
				else {
					exit(); // This onClick function
				}
			}
		}
	if (myWindow.show() == 1) { // User didn't click the cancel button
		return [myWidthField.text, myHeightField.text,
			myQualityField.selection.text, myFormatMethodField.selection.text, myColorSpaceField.selection.text, 
			myColorProfileField.value, myAliasField.value, myOverprintField.value];
	}
	else {
		return; // This dialog function
	}
}


Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Dec 08, 2021 Dec 08, 2021

Copy link to clipboard

Copied

Hello @Mike Bro 

 

So I figured, your Code would be the things I needed. Do you know how to scale the exportet jpg's, so their heigth and width are correct? 

Like I mentioned in the Reply above, the jpg's are exported in the wrong size. Haven't found out, how to export with the right height and size.

 

Thanks for youre help in advance, your my lifesafer!

OPTEN

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Dec 08, 2021 Dec 08, 2021

Copy link to clipboard

Copied

The JPEG export exports the entire page or a selection. An InDesign Layer doesn’t have a dimension—it can contain page items that do, which would be pageItem[i].geometricBounds in JS.

 

@Mike Bro ’s script is exporting the entire page with the targeted layer visible, so the export would be the page as the canvas, with the visible Layer’s pageitems positioned on the canvas.

 

If you are trying to export a page item as a JPEG it could be done but I think it would be more complex

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Dec 08, 2021 Dec 08, 2021

Copy link to clipboard

Copied

Good Morning @rob day 

 

I see the Problem here. Can't I group the children of the Layer and then exportFile() those?

Is your Trick to do it, with the pageItem[i].geometricBounds?

 

A other question is, if it would make sence to export the selection of the Doc. In my understanding, that would work. Would you know a way to get the name of something selected?

Sorry for wasteing your time,

OPT10

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Dec 09, 2021 Dec 09, 2021

Copy link to clipboard

Copied

Yes you can export a selection. Selection is an array, so if the selection is more than one object you would have to handle how to group the pageitems. It could get complicated if the page items are on different layers. By default a page item’s name returns as nothing unless it has been named in the Layers panel, but the name could also be scripted. Something like this, which exports to the desktop:

 

 

 

app.jpegExportPreferences.properties = {
    antiAlias: true,
    embedColorProfile: true,
    exportResolution: 72,
    jpegColorSpace: JpegColorSpaceEnum.RGB,
    jpegQuality: JPEGOptionsQuality.maximum,
    simulateOverprint: false,
  }

var sel = app.documents[0].selection[0];
var lay = sel.itemLayer;
var pin = sel.name;
//sel.name returns as "" by default
if (sel.name == "") {
	pin = "mySelection"
} 

//the jpg name for export—the selection’s Layer - the selection’s name + .jpg
var fn = "/" + lay.name + "-" + pin +".jpg"
$.writeln(sel.name)

sel.exportFile(ExportFormat.jpg, File(Folder.desktop + fn));

 

 

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Dec 10, 2021 Dec 10, 2021

Copy link to clipboard

Copied

@rob day 

You're the man! With a few changes and your Script, it works!

 

For everyone wondering how to do it, this is my take, bases on @rob day 's soulution:

 

app.jpegExportPreferences.properties = {
	antiAlias: true,
	embedColorProfile: true,
	exportResolution: 300,
	jpegColorSpace: JpegColorSpaceEnum.RGB,
	jpegQuality: JPEGOptionsQuality.maximum,
	simulateOverprint: false,
}

	var myFolder = Folder.selectDialog ("Select location to export the Jpeg files.");
	if (myFolder != null) {
		var mySelection = app.selection;
		if (mySelection.length > 0) {
			for (var i = 0; i < mySelection.length; i ++) {
				var exportedSelected = mySelection[i];
				var selectedLayer = exportedSelected.itemLayer;				
				var layerName = "/" + selectedLayer.name + ".jpg";
				exportedSelected.exportFile(ExportFormat.jpg, File(myFolder + layerName));		
			}		
		} else {
			alert("Please select at least one Layer!");
		}		
	}

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Dec 10, 2021 Dec 10, 2021

Copy link to clipboard

Copied

Hi @OPTEN , One thing you might want to check—if the selection’s page items are all in the same layer, the JPEG exports are overwriting themselves. Here my selection contains 3 page items on the layer named Layer 1, and only the last item in the loop is getting saved because all three export with the same name:

 

Screen Shot 10.png

 

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Dec 09, 2021 Dec 09, 2021

Copy link to clipboard

Copied

Also, if you set the export resolution to 72ppi, the exported pixel dimensions will match the InDesign dimensions if your ruler units are set to Pixels. If the document isn’t set up as Pixels you can set a target pixel by dividing the target pixel width by the width in inches.

 

EDIT: And you can temporarily group all of the items in a page’s layer and set the group as the selection–something like this:

 

 

 

 

//the export pixel width
var pxwidth = 1200
//the active page
var ap = app.activeWindow.activePage;
//the layer to target
var lyr = app.documents[0].layers.itemByName("MyLayer");
//group the layer‘s page items and select the group
var sel = app.selection = tempGroup(ap,lyr);
//sets the export pixel width
var res = getRes(sel, pxwidth)
//the jpg name for export—the page name - the layer’s name + .jpg
var fn = "/"+"Pg." + ap.name +"_"+ lyr.name +".jpg"


//export settings
app.jpegExportPreferences.properties = {
    antiAlias: true,
    embedColorProfile: true,
    exportResolution: res,
    jpegColorSpace: JpegColorSpaceEnum.RGB,
    jpegQuality: JPEGOptionsQuality.maximum,
    simulateOverprint: false,
}

sel.exportFile(ExportFormat.jpg, File(Folder.desktop + fn));

//ungroup the selection
sel.ungroup();


/**
* Get pixel dimension export resolution 
*  the page item to export 
*  the target pixel width 
*  the resolution to export 
* 
*/
function getRes(pi, pd){
    app.scriptPreferences.measurementUnit = MeasurementUnits.INCHES
    var b = pi.geometricBounds;
    var w = b[3]-b[1];
    return pd/w
}


/**
* Group a layer’s page items 
*  the page to target 
*  the layer to group 
*  the group 
* 
*/
function tempGroup(p,l){
    var lyrItems = l.pageItems;
    var gp=[];
    for (var i = 0; i < lyrItems.length; i++){
        if (lyrItems[i].parentPage == p) {
            gp.push(lyrItems[i])
        } 
    }; 
    return app.documents[0].groups.add(gp, l)
}


 

 

 

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
New Here ,
Mar 01, 2023 Mar 01, 2023

Copy link to clipboard

Copied

LATEST

Hi, I use this javascript in Indesign 2021 to export an intire book to JPGs, to a folder Desktop/JPG
It uses the same Embed color profile you have by default on Export - JPG
The rest of the preferences are preaty simple 
Note, this script does not stop for user interaction, ex missing fonts, links etc -
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
Note 2: Uou need to have just 1 opened book for this to work, I think

Script
app.jpegExportPreferences.exportingSpread = false;  
app.jpegExportPreferences.jpegExportRange = ExportRangeOrAllPages.EXPORT_ALL;  
app.jpegExportPreferences.jpegRenderingStyle = JPEGOptionsFormat.BASELINE_ENCODING;  
app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.HIGH; 
app.jpegExportPreferences.embedColorProfile = true; 
app.jpegExportPreferences.exportResolution = 300;
app.jpegExportPreferences.jpegColorSpace = JpegColorSpaceEnum.RGB;
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
if (app.books.length != 1)  
     alert ("This only works when you have one (1) book open");  
else  
     for (b=0; b<app.books[0].bookContents.length; b++)  
     {  
          c = app.open(app.books[0].bookContents[b].fullName);  
          c.exportFile (ExportFormat.JPG, File("~/Desktop/JPG/"+app.books[0].bookContents[b].name+".jpg"));
          app.activeDocument.close(SaveOptions.no);  
     }
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.INTERACT_WITH_ALL;  

FredCN

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines