Author Topic: Script For Shuffle (Random)  (Read 2750 times)

0 Members and 1 Guest are viewing this topic.

nightslayer23

  • Newbie
  • *
  • Posts: 98
Script For Shuffle (Random)
« on: October 12, 2022, 06:48:32 AM »
Hi again, would you be able to write a custom script for shuffling the PDF page order from a multipage pdf?

RTT

  • Administrator
  • *****
  • Posts: 918
Re: Script For Shuffle (Random)
« Reply #1 on: October 13, 2022, 01:54:28 AM »
Check if this works.
Code: [Select]
var Merger = pdfe.CreateDocumentMerger();
var ProgressBar = pdfe.ProgressBar;
ProgressBar.max = pdfe.SelectedFiles.Count;
var MainPageIndex = 0;
for (var i = 0; i < pdfe.SelectedFiles.Count; i++) {
    var File = pdfe.SelectedFiles(i);
    var Filename = File.Filename;
    pdfe.echo('Shuffling ' + Filename);
    ProgressBar.position = i + 1;
    var Pages = File.Pages;
    ShuffledIndexesArray = createShuffledIndexesArray(Pages.Count);

    for (var p = 0; p < ShuffledIndexesArray.length; p++) {
        var Page = Pages(ShuffledIndexesArray[p]);
        Merger.MergePage(Page);
    }
    var newFilename = Filename.substring(0, Filename.lastIndexOf('.')) + '_Shuffled.pdf';
    Merger.EndAndSaveTo(newFilename);
    pdfe.echo(' [OK]', 0, 1);
}
pdfe.echo('Done.');

/*https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
Randomize array in-place using Durstenfeld shuffle algorithm */
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

function createShuffledIndexesArray(N) {
    var Indexes = [];
    for (var i = 0; i < N; i++) {
        Indexes.push(i);
    }
    shuffleArray(Indexes);
    return Indexes
}

nightslayer23

  • Newbie
  • *
  • Posts: 98
Re: Script For Shuffle (Random)
« Reply #2 on: October 13, 2022, 02:59:12 AM »
worked perfectly   ;D ;D thankyou again!