Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Indesign script for converting page numbers to percentages.
// Version.1.0.
// Page Numbers To Percentages.jsx
// https://gist.github.com/joonaspaakko/6628e2b6252d622b1b7f7eba601f6c91
// You may want to save before running the script. Every single
// time you run the script, all text frames that are inside a
// master page or nested master pages will be torn out (overridden).
// The script assumes the starting point is this:
// 1. You have a designated layer for the page numbers (Layer name defined below↓).
// 2. The layer should only contain one empty textframe per page. The text frame could contain text too, but it will be overweritten so it doesn't really matter.
// - The text frame can be inside a master page or a regular page.
var layerName = "Page Numbers";
var basedOn = 1; // 0 = Puts back the current page number, 1 = The numbered pages, 2 = All pages
var percentage_prefix = '';
var percentage_suffix = '%';
if ( app.documents.length > 0 ) {
var doc = app.activeDocument;
var targetLayer = null;
var layer = doc.layers.itemByName( layerName );
var numberItems = prepareNumberOverride( doc, layer );
replacePageNumbers( layer, numberItems );
}
function prepareNumberOverride( doc, layer ) {
var collect_items = [];
for ( var pageIndex=0; pageIndex < doc.pages.length; pageIndex++ ) {
var page = doc.pages[pageIndex];
var nPageItems = page.textFrames;
var mPageItems = page.masterPageItems;
var pageItemAdded = false;
for ( var nPageItemIndex=0; nPageItemIndex < nPageItems.length; nPageItemIndex++ ) {
var textFrame = nPageItems[ nPageItemIndex ];
if ( textFrame.itemLayer == layer ) {
collect_items.push( textFrame );
pageItemAdded = true;
}
}
if ( !pageItemAdded ) {
for ( var mPageItemIndex=0; mPageItemIndex < mPageItems.length; mPageItemIndex++ ) {
var item = mPageItems[ mPageItemIndex ];
if ( item.itemLayer === layer ) {
var text = item.contents;
item.allowOverrides = true;
if ( item.allowOverrides == true ) {
var newItem = item.override( page );
collect_items.push( newItem );
}
}
}
}
}
return collect_items;
}
function replacePageNumbers( layer, numberItems ) {
var numberItemsLength = numberItems.length;
for ( var i=0; i < numberItems.length; i++ ) {
var numberItem = numberItems[i];
var currentPageNumber = numberItem.parentPage.name;
// Based on all number pages...
if ( basedOn == 1 ) {
var percentage = Math.floor( ((i+1) / numberItemsLength) * 100 );
}
// Based on all pages...
else if ( basedOn == 2 ) {
var percentage = Math.floor( (currentPageNumber / app.activeDocument.pages.length) * 100 );
}
numberItem.contents = basedOn == 0 ? currentPageNumber : percentage_prefix + percentage + percentage_suffix;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment