Recently, a friend of mine wanted me to randomize PDF documents that he downloaded. These were Sudoku puzzles with two puzzles per page and in ascending order from least to most difficult. As he printed these, he wanted a diversity of difficulty, hence the randomization request. The largest PDF that I have tested it with is 190 pages and near instantaneous PDF output.
Here is the ASOC code I came up with to do this. It gets an array of PDF page numbers and then shuffles that array to avoid page number duplication.
The code:
-- PDF_random_pagegen.applescript
-- randomize input PDFs pages to output PDF
-- Tested: Tahoe 26.0.1, 26.1, 26.2
-- VikingOSX, 2025-10-30, Apple Support Communities, No warranties implied.
use framework "Foundation"
use framework "PDFKit"
use framework "GamePlayKit"
use scripting additions
property ca : current application
property OUTSUFFIX : "_rdm"
set origPage to ca's NSMutableArray's array()
set randomPage to ca's NSMutableArray's array()
set outFileStr to ca's NSMutableString's |string|()
set thisPDF to POSIX path of (choose file of type "PDF") as text
set pdf to ca's PDFDocument's alloc()'s initWithURL:(ca's NSURL's fileURLWithPath:thisPDF)
set outPDF to ca's PDFDocument's alloc()'s init()
-- strip extension and append a _rand suffix to the original PDF name as the recipient PDF
outFileStr's setString:((ca's NSString's stringWithString:thisPDF)'s stringByDeletingPathExtension())
outFileStr's appendFormat_("%@.pdf", OUTSUFFIX)
set pageCnt to pdf's pageCount()
-- PDF page indexes are zero-based and here we generate the page numbers from the
-- pageCount
repeat with ndx from 0 to (pageCnt - 1)
(origPage's addObject:ndx)
end repeat
-- by shuffling, we avoid any page number duplication
randomPage's setArray:((ca's GKRandomSource's sharedRandom)'s arrayByShufflingObjectsInArray:origPage)
-- now randomly append pages from the original PDF
repeat with ndx in randomPage
set thisPage to (pdf's pageAtIndex:ndx)
(outPDF's insertPage:thisPage atIndex:(outPDF's pageCount()))
end repeat
set finalPDF to outPDF's dataRepresentation()
-- and write the random page PDF to the original PDF location
finalPDF's writeToFile:outFileStr atomically:true
return