How to get HTML data out of of the OS X pasteboard / clipboard?

纵然是瞬间 提交于 2019-12-03 09:32:54

问题


I do have to send a report regarding pasting some clipboard content into a web rich editor and I need a way to dump/restore the clipboard content to (probably) HTML.

How can I do this?

It seems that pbcopy / pbpaste do alway give me text even if I use the pbpaste -P rtf or pbpaste -P HTML


回答1:


Three years later, in more civilized times, we have Swift. You can write a short Swift script to pull exactly what you need off of OS X's pasteboard.

Put the following Swift 4 snippet into a new text file. I named mine pbpaste.swift:

import Cocoa
let type = NSPasteboard.PasteboardType.html
if let string = NSPasteboard.general.string(forType:type) {
  print(string)
}
else {
  print("Could not find string data of type '\(type)' on the system pasteboard")
  exit(1)
}

Then, copy some html, and run swift pbpaste.swift from the directory where you put that file.

Yay, html! Uggh, OS X added a ton of custom markup (and a <meta> tag?!) — but hey, at least it's not plain text!

Notes:

  • NSPasteboard.PasteboardType.html is a special global that evaluates to the string "public.html"
  • Obviously this is html specific, so you'd probably want to either:
    1. Name it pbpaste-html.swift, or
    2. Read the desired type from the command line arguments
  • It's kind of slow, because it's being interpreted on the fly, not compiled and executed. Compilation gives me a 10x speed-up:

    xcrun -sdk macosx swiftc pbpaste.swift -o pbpaste-html
    

    Then just call ./pbpaste-html instead of swift pbpaste.swift.




回答2:


I realise you've already found this, but for the benefit of people who turn up here from Google, the solution given for RTF data at Getting RTF data out of Mac OS X pasteboard (clipboard) works fine for getting HTML out of the clipboard, too.

That is, the command

osascript -e 'the clipboard as «class HTML»' |   perl -ne 'print chr foreach unpack("C*",pack("H*",substr($_,11,-3)))'


来源:https://stackoverflow.com/questions/17217450/how-to-get-html-data-out-of-of-the-os-x-pasteboard-clipboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!