Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Generate RTF clippings with Python and pbcopy UNIX

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...]
    •    
  • Currently 1.00 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (1 vote cast)
 
[6,515 views]  

Generate RTF clippings with Python and pbcopy | 1 comments | Create New Account
Click here to return to the 'Generate RTF clippings with Python and pbcopy' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Don't use pbcopy
Authored by: laotzu on Sep 04, '03 09:22:16AM

Python comes with a rich set of libraries, including wrappers for carbonlib. It is much nicer to use these libraries to access the pasteboard rather than pbcopy, since you can explicitly state the types of data you want to put on the board. Additionally, this way a new process does not need to be spawned. In place of the last three lines of code, use this instead:

from Carbon import Scrap
Scrap.ClearCurrentScrap()
Scrap.GetCurrentScrap().PutScrapFlavor('RTF ', 0, content)


[ Reply to This | # ]