I improved upon Swift code from AI that writes Page numbers on PDFs. It works like a charm on macOS 27.2.
I then migrated that Swift functionality to an AppleScript/Objective-C solution that runs without error in Script Editor and Script Debugger — and produces an output PDF - without page numbers. The Page annotation dict is showing all relevant fields becoming populated prior to adding the annotation back to the PDFPage object. So I am baffled…
I would appreciate help getting this ASOC solution to write page numbers to PDFs as I have spent hours on it in frustration.
use framework "AppKit"
use framework "PDFKit"
use AppleScript version "2.5"
use scripting additions
property ca : current application
set inPDF to POSIX path of (choose file of type "PDF" default location (path to desktop)) as text
set outPDF to (ca's NSString's stringWithString:inPDF)'s stringByDeletingPathExtension()'s stringByAppendingString:"_nbr.pdf"
my addPageNumbers(inPDF, outPDF)
return
on addPageNumbers(inputPDF, outPDF)
set inURL to ca's NSURL's fileURLWithPath:inputPDF
set outURL to ca's NSURL's fileURLWithPath:outPDF
set pdf to ca's PDFDocument's alloc()'s initWithURL:inURL
set pageCnt to pdf's pageCount()
set nilDict to ca's NSDictionary's dictionary()
repeat with i from 0 to pageCnt - 1
set thisPage to (pdf's pageAtIndex:i)
set pageNo to (i + 1) as text
set itsBounds to (thisPage's boundsForBox:(ca's kPDFDisplayBoxCropBox))
-- keep everything in NSRect for macOS Annotations
set itsX to ca's NSMinX(itsBounds)
set itsY to (ca's NSMinY(itsBounds)) + 24
set itsWidth to (ca's NSWidth(itsBounds)) - 36
set itsHeight to 20
set adaptedBounds to ca's NSMakeRect(itsX, itsY, itsWidth, itsHeight)
set anno to (ca's PDFAnnotation's alloc()'s initWithBounds:adaptedBounds forType:(ca's PDFAnnotationSubTypeFreeText) withProperties:nilDict)
(anno's setContents:pageNo)
(anno's setFont:(ca's NSFont's systemFontOfSize:12))
(anno's setFontColor:(ca's NSColor's darkGrayColor()))
(anno's setColor:(ca's NSColor's darkGrayColor()))
(anno's setBackgroundColor:(ca's NSColor's clearColor()))
(anno's setAlignment:(ca's NSTextAlignmentRight))
log ((anno's annotationKeyValues)'s |description|()) as text
(thisPage's addAnnotation:anno)
end repeat
pdf's writeToURL:outURL
return
end addPageNumbers