I was recently asked if it was possible to print text on the clipboard without the need to open another application to paste it into. One easy way to do this is to create an applescript, seems an easy thing to do but there are a couple of interesting aspects that make this worth sharing.
One way to print in the background is to use the UNIX "lp " command, there is an excellent summary of UNIX printing here.
However when you copy text to the clipboard if often contains invisible non-printing characters that can cause lp to fail. So first we we convert the text to plain text and remove any application specific formatting. The as text portion grabs the stylized text from whatever other junk may be surrounding it (which can be significant), as record splits out the style and text portions, and «class ktxt» grabs the plain text portion of that.
The text is then written to a file the location of which is defined within the temporary items folder.
lp is then used to print the file.
If you want to see how you might use this have a look here.
set the clipboard to «class ktxt» of ((the clipboard as text) as record) set the_clip to the clipboard --Comment out if not needed display dialog the_clip tell application "Finder" to set the_folder to (path to temporary items folder) as text --If you want to keep the file use --tell application "Finder" to set the_desktop to (path to desktop folder) as text set target_file to the_folder & "JUNK" --display dialog target_file my write_to_file(the_clip, target_file, false) set posix_path to POSIX path of target_file --display dialog posix_pathsw set to_print to "lp " & posix_path do shell script to_print --For testing --tell application "Terminal" --activate --do script to_print --end tell on write_to_file(this_data, target_file, append_data) try set the target_file to the target_file as text set the open_target_file to ¬ open for access file target_file with write permission if append_data is false then ¬ set eof of the open_target_file to 0 write this_data to the open_target_file starting at eof close access the open_target_file --display dialog "file_done" return true on error try close access file target_file end try return false end try end write_to_file
You can download the script here