Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apple Script : How can I copy html content to the clipboard?

I know how to copy plain text to the clipboard:

oascript -e 'set the clipboard to "plain text"'

But the question is how can I copy html contents to the clipboard? For example, how can I copy the following html content to the clipboard:

<b>bold text</b>

so that I get bold text when I paste it in TextEdit?

Thanks for the help in advance!


I found an intermediate solution for this:

echo "<b>bold text</b>" | textutil -stdin -stdout -format html -convert rtf | pbcopy

This works, so far so good, but unfortunately I found that it doesn't work for an image tag:

echo "<img src=\"https://www.google.com/images/srpr/logo3w.png\">" | textutil -stdin -stdout -format html -convert rtf | pbcopy

This does not do the job I want, so anybody knows the reason?
Thanks!


I've found a working solution and posted it below :)

like image 857
K J Avatar asked Jun 18 '12 15:06

K J


2 Answers

The solution by @k-j would not work if the input HTML is too big, you might encounter some error messages like below:

/usr/bin/osascript: Argument list too long

I made some improvements to @k-j's solution by converting it to an executable and handling data via pipe. I hope it helps as well.

Executable

~/bin/pbcopyhtml:

#!/bin/sh
printf "set the clipboard to «data HTML$(cat $@ | hexdump -ve '1/1 "%.2x"')»" | osascript -

Usage

from pipe

$ printf '# title\n\n- list\n- list' | cmark | ~/bin/pbcopyhtml
$ osascript -e 'the clipboard as record'
«class HTML»:«data HTML3C68313E7469746C653C2F68313E0A3C756C3E0A3C6C693E6C6973743C2F6C693E0A3C6C693E6C6973743C2F6C693E0A3C2F756C3E0A»

from file

$ printf '# title\n\n- list\n- list' | cmark > sample.html
$ ~/bin/pbcopyhtml sample.html
$ osascript -e 'the clipboard as record'
«class HTML»:«data HTML3C68313E7469746C653C2F68313E0A3C756C3E0A3C6C693E6C6973743C2F6C693E0A3C6C693E6C6973743C2F6C693E0A3C2F756C3E0A»
like image 77
Weihang Jian Avatar answered Sep 16 '22 13:09

Weihang Jian


I've found a solution and the idea is to use the HTML class directly instead of the RTF class. (TextEdit or web editors can handle this HTML class as well as the RTF class data)
All you have to do is to convert your html code into raw hexcode.
The complete code looks like:

hex=`echo -n "your html code here" | hexdump -ve '1/1 "%.2x"'`
osascript -e "set the clipboard to «data HTML${hex}»"

You can combine them into one sentence, of course.
Hope this helped anybody interested. :)

like image 43
K J Avatar answered Sep 20 '22 13:09

K J