Writing paragraph centered text at top of a PDF document

Borrowing from examples provided by Shane, I attempted to overlay a pdf with paragraph-centered text at the top of the pdf document. For unknown reasons, my paragraph will not center. Perhaps, I need to create a rectangle at the top of the document, but I am not sure as to that method.
I would appreciate any help on methods using the framework “AppKit” or any other framework for that purpose.

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set theFile to POSIX path of (choose file with prompt "Choose an image file")

#      Build path for exported image
set theFile to current application's NSString's stringWithString:theFile
set newPath to (theFile's ¬
	stringByDeletingPathExtension()'s ¬
	stringByAppendingString:"-out")'s ¬
	stringByAppendingPathExtension:"jpg"

#      Make NSString of the text, and define text attributes
set StringToAdd to "This image was superimposed at " & (current date)
set theNSString to current application's NSString's stringWithString:StringToAdd
set theNSFont to current application's NSFont's fontWithName:"Helvetica" |size|:10
set theNSColor to current application's NSColor's redColor()
set theParStyle to current application's NSParagraphStyle's defaultParagraphStyle()'s mutableCopy()
theParStyle's setAlignment:(current application's NSTextAlignmentCenter)
set styleAttributesNSDictionary to current application's NSDictionary's ¬
	dictionaryWithObjects:{¬
		theNSColor, ¬
		theNSFont, ¬
		theParStyle} ¬
		forKeys:{¬
		current application's NSForegroundColorAttributeName, ¬
		current application's NSFontAttributeName, ¬
		current application's NSParagraphStyleAttributeName}

#      Create new image
set theNSImage to current application's NSImage's alloc()'s initWithContentsOfFile:theFile

#      Lock  focus on the view, to allow  subsequent commands  in the view’s window to  coordinate a system.
theNSImage's lockFocus()

#      Set target coordinates to a region, nearly at the top of the page, based upon an origin at the page's bottom left.
set TranslationCoordinates to {20, 760}

#      Write the NSString at those target coordinates with attributes
theNSString's drawAtPoint:TranslationCoordinates withAttributes:styleAttributesNSDictionary

#      Unlock focus
theNSImage's unlockFocus()

set theNSData to theNSImage's TIFFRepresentation()

#      Make a bitmap image representaion from the data
set theNSBitmapImageRep to (current application's NSBitmapImageRep's ¬
	imageRepsWithData:theNSData)'s ¬
	objectAtIndex:0

#      Create jpeg data from the bitmap image rep
set newNSData to theNSBitmapImageRep's ¬
	representationUsingType:(current application's NSJPEGFileType) ¬
		|properties|:{NSImageCompressionFactor:0.8, NSImageProgressive:false}

#      Save it to a file
newNSData's ¬
	writeToFile:newPath ¬
		atomically:true


You will need to do something like get the size of the string using sizeWithAttributes:, get the width from that, and use that and the width of the image to work out where to start the text. Paragraph centering is pretty much irrelevant for single-line paragraphs.

My attempt to substitute drawAtPoint with drawInRect failed.
In place of:

#    Write the NSString at those target coordinates with attributes
theNSString's drawAtPoint:TranslationCoordinates withAttributes:styleAttributesNSDictionary

I substituted the following code.


#    Create an attributed string containing text and style
set attributedString to current application's NSAttributedString's alloc()'s initWithString:theNSString attributes:styleAttributesNSDictionary

#    Round up floating numbers to integers, from data gathered from attributed string's  size 
set theWidth to round (width of attributedString's |size|()) rounding up
set theHeight to round (height of attributedString's |size|()) rounding up

#    Draw in rectangle errs!
attributedString's drawInRect:{origin:{x:20, y:760}, |size|:{width:theWidth, height:theHeight}} fromRect:(current application's NSZeroRect) operation:(current application's NSCompositeSourceOver) fraction:1.0 respectFlipped:false hints:(missing value)

The command to drawInRect however erred with the following AppleScript Execution Error:

What might be possible solutions to drawing a string in a rectangle?

You don’t want/need to draw the text in a rectangle. You were drawing it correctly before – you just need to calculate where to draw it. See my previous post.

I will help with this. Thanks for nice script:


use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSString : a reference to current application's NSString
property NSFont : a reference to current application's NSFont
property NSColor : a reference to current application's NSColor
property NSDictionary : a reference to current application's NSDictionary
property NSImage : a reference to current application's NSImage
property NSBitmapImageRep : a reference to current application's NSBitmapImageRep

set theFile to POSIX path of (choose file with prompt "Choose an image file")
set StringToAdd to "This image was superimposed at " & (current date)

-- Build path for exported image
set theFile to NSString's stringWithString:theFile
set newPath to (theFile's stringByDeletingPathExtension()'s stringByAppendingString:"-out")'s ¬
	stringByAppendingPathExtension:"jpg"

-- Make NSString of the text, and define text attributes
set theNSString to NSString's stringWithString:StringToAdd
set theNSFont to NSFont's fontWithName:"Helvetica" |size|:10
set theNSColor to NSColor's redColor()
set styleAttributesNSDictionary to NSDictionary's dictionaryWithObjects:{theNSColor, theNSFont} ¬
	forKeys:{"NSColor", "NSFont"}
set stringWidth to width of (theNSString's sizeWithAttributes:styleAttributesNSDictionary)

-- Create new image
set theNSImage to NSImage's alloc()'s initWithContentsOfFile:theFile
set imageWidth to theNSImage's |size|()'s width()

-- Lock focus, to draw in the view’s window .
theNSImage's lockFocus()

-- Set target coordinates to the top of the page, based upon an origin at the page's bottom left.
set TranslationCoordinates to {(imageWidth - stringWidth) / 2, 760}

-- Write the NSString at those target coordinates with attributes
theNSString's drawAtPoint:TranslationCoordinates withAttributes:styleAttributesNSDictionary

-- Unlock focus
theNSImage's unlockFocus()

-- Make a bitmap image representaion from the data
set theNSData to theNSImage's TIFFRepresentation()
set theNSBitmapImageRep to (NSBitmapImageRep's imageRepsWithData:theNSData)'s objectAtIndex:0

-- Create jpeg data (enumeration=3) from the bitmap image rep
set newNSData to theNSBitmapImageRep's representationUsingType:3 ¬
	|properties|:{NSImageCompressionFactor:0.8, NSImageProgressive:false}

-- Save it to a file
newNSData's writeToFile:newPath atomically:true