After getting feedback that my original clipboard code doesn't handle all scenarios, especially with Chrome, I went back to the code to get a better understand of what's going on and find the correct way to set plain text and HTML snippet to clipboard.
- Setting plain text and html data.
- Unicode support for plain text.
- Clipboard HTML format
- Parts start/end offsets.
- StartFragment/EndFragment comments.
- <html> and <body> elements.
- Unicode handling.
In case you want to display HTML with highlighted/colored syntax the simplest way to go is use WinForms RichTextBox, all is needed is to add RTF color tags surrounding HTML elements.
This helper class goal is exactly that, given a string containing HTML code it will return an RTF formatted string with the HTML elements colored.
I have used Alun Evans code as base, improving its coloring support and performance.
See it's usage in HtmlRenderer project.
The requirement to generate image from HTML snippet appears to be quite popular, as seen in a few StackOverflow questions1, so I have decided to properly support it in HTML Renderer to simplify the process and improve the results.
The support for image generation in HTML Renderer existed since day one, but it required manual handling of image graphics object, size limitations and configuration toggles.
Additionally the change to use GDI text rendering in 184.108.40.206 broke2 the most common code used for generating image with HTML Renderer, as provided in several blogs and StackOverflow answers3.
Working on adding text selection and copy-paste to HTML Renderer I wanted to add rich text copy capability.
My first thought was to use Clipboard.SetText method with TextDataFormat.Html but to my surprise it just didn’t work. Turning to Google I finally found this post, harder to find than what I expected, that explained what needs to be done.
Apparently when setting html text you need to provide a header with additional information to what fragment of the html you actually want to paste while being able to provide additional styling around it:
Managed HTML rendering is a pain in the ass for a really long time, a really good solution I was able to find is this HTML Renderer hosted on CodePlex, though the project seems to be dead and I'm not sure how I can contribute… Anyway, It's 100% managed code and has nice HTML 4 and CSS level 2 spec cover.
So I decided to check it out and after a little playing around it felt a bit heavy so I decided to look into its performance using built in visual studio profiler, to ruin the ending I have managed to reduce average render time from 282 msec to 24 msec (91%).
The final code with most of the issues fixes raised here and here can be found here, you can use it under the same license the original code is under. Also, if everything goes well, I might be adding features to the project including text selecting for copy-paste support.