private Bitmap RenderHtml(Size maxSize, string html, Dictionary<string, Image> images) { // encode the HTML page text to bytes byte[] htmlData = Encoding.UTF8.GetBytes(html); using (HTMLite hLite = new HTMLite()) { // this callback is used to load images hLite.UriHandler = (uri, type) => LoadUri(uri, type, images); // load the HTML page data hLite.LoadHtmlFromMemory("content.html", htmlData); // set the HTML page size to the maximum size Size size = maxSize; hLite.Measure(size.Width, size.Height); // detect the actual size var bounds = hLite.GetRootElement().Select("#bounds"); if (bounds.Count > 0) { size = bounds[0].Bounds.Size; size.Width += bounds[0].Bounds.Left * 2; size.Height += bounds[0].Bounds.Top * 2; } hLite.Measure(size.Width, size.Height); // render the HTML page to the image Bitmap img = new Bitmap(size.Width, size.Height, pixFormat); using (Graphics g = Graphics.FromImage(img)) { g.Clear(Color.Transparent); hLite.Render(g, 0, 0, img.Width, img.Height); } return img; } }
private byte[] LoadUri(string uri, HTMLite.ResourceType type, Dictionary<string, Image> images) { Image img; if (images.TryGetValue(uri, out img)) { // serialize the image to a stream of bytes using (MemoryStream ms = new MemoryStream()) { lock (gdiLock) { img.Save(ms, imgFormat); } byte[] data = ms.ToArray(); return data; } } return null; }