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 :)
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.
~/bin/pbcopyhtml:
#!/bin/sh
printf "set the clipboard to «data HTML$(cat $@ | hexdump -ve '1/1 "%.2x"')»" | osascript -
$ printf '# title\n\n- list\n- list' | cmark | ~/bin/pbcopyhtml
$ osascript -e 'the clipboard as record'
«class HTML»:«data HTML3C68313E7469746C653C2F68313E0A3C756C3E0A3C6C693E6C6973743C2F6C693E0A3C6C693E6C6973743C2F6C693E0A3C2F756C3E0A»
$ printf '# title\n\n- list\n- list' | cmark > sample.html
$ ~/bin/pbcopyhtml sample.html
$ osascript -e 'the clipboard as record'
«class HTML»:«data HTML3C68313E7469746C653C2F68313E0A3C756C3E0A3C6C693E6C6973743C2F6C693E0A3C6C693E6C6973743C2F6C693E0A3C2F756C3E0A»
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With