Generate RTF clippings with Python and pbcopy

Sep 04, '03 07:50:00AM

Contributed by: MitchChapman

Python (included with 10.2) makes it easy to build text from templates, replacing placeholder tags with custom content. Python together with pbcopy lets you make rich text (RTF) from templates and share it via the pasteboard. pbcopy usually pastes its stdin as plain text. But if stdin starts with an RTF or Encapsulated Postscript header, pbcopy will paste as RTF or EPS, respectively. Here's an example which puts a rich-formatted timestamp onto the pasteboard:


#!/usr/bin/env python

import sys, os, time

# The RTF content goes into the template string, _template.
# Python formatting directives like %(dateReported)s are embedded
# in the RTF content.  For example, the following _template
# should produce RTF which looks something like
#     <b>Date Reported:</b>     Wed Sep  3 08:41:03 2003
#
# NOTE:  _template must be a raw string (indicated by the "r" before
# the triple quotes).  Otherwise RTF markup could be mangled, e.g. by
# turning \rtf1 into <carriage return>tf1

_template = r"""{\rtf1\mac\ansicpg10000\cocoartf102
{\fonttbl\f0\fswiss\fcharset77 Helvetica-Bold;\f1\fswiss\fcharset77 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh9000\viewkind0
\pard\tx720\tx791\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\ql\qnatural

\f0\b\fs24 \cf0 Date Reported:
\f1\b0      %(dateReported)s\
}
"""

content = _template % {'dateReported': time.ctime(time.time())}

outf = os.popen("pbcopy", "w")
outf.write(content)
outf.close()
[robg adds: Create the script, make it executable (chmod 755 script_name), and then call it. Switch to an RTF-capable application such as TextEdit (in RTF mode, of course), and hit paste. You should get an RTF string noting the current date and time. This hint is obviously only an example of what you can do with RTF pasteboard content...]

Comments (1)


Mac OS X Hints
http://hints.macworld.com/article.php?story=200308311113498