Skip to content
Advertisement

How to write javascript to reorder pages of a pdf document?

I have a double-sided document as two separate pdf files — front-facing pages in one document and rear-facing pages in the second.

front.pdf
rear.pdf

I have also combined them into a single document with all the pages but with all the front-facing pages before the rear-facing pages. The page ordering is of the form, {1,3,5,7,...,[n],2,4,6,8,...,[n-1 OR n+1]}

all.pdf

I wish to write a simple javascript that can be run from inside Adobe Abrobat X Pro. Ideally, it would count the pages of the document all.pdf, handle both occasion when there are either an odd or even number of total pages and then reorder them such that they are in their original order:

page [1>3>4>2] => page [1>2>3>4]

The tiny leading code snippet above is from the answer by user171577 on SuperUser in this question: https://superuser.com/questions/181596/software-that-merges-pdf-every-other-page

Advertisement

Answer

I was able to accomplish this following advice from NullUserException :

This script requires a document composed of all the odd pages followed by all the even pages. It will cope with cases where there are n even pages and n+1 odd pages.

I entered a ‘Document JavaScript’ called InterleavePages, with the following code:

function InterleavePages() {

var n = this.numPages;
var nOdd = Math.floor(n / 2);
var nEven = n - nOdd;
var x;
var y;
var i;

for(i = 0; i < nEven; i++) {
                         // movePage x, toAfterPage y
                         // note page numbers are 0-indexed
    x = nOdd + (i);      //
    y = i * 2     ;      //  
    this.movePage(x,y); 
   }
}
InterleavePages();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement