-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathHtmlString.cs
More file actions
82 lines (72 loc) · 2.89 KB
/
HtmlString.cs
File metadata and controls
82 lines (72 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright © 2019 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.IO;
using System.Text;
namespace CefSharp.Web
{
/// <summary>
/// Represents an raw Html (not already encoded)
/// When passed to a ChromiumWebBrowser constructor, the html will be converted to a Data Uri
/// and loaded in the browser.
/// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs for details
/// </summary>
public class HtmlString
{
private readonly string html;
private readonly bool base64Encode;
private readonly string charSet;
/// <summary>
/// Initializes a new instance of the HtmlString class.
/// </summary>
/// <param name="html">raw html string (not already encoded)</param>
/// <param name="base64Encode">if true the html string will be base64 encoded using UTF8 encoding.</param>
/// <param name="charSet">if not null then charset will specified. e.g. UTF-8</param>
public HtmlString(string html, bool base64Encode = false, string charSet = null)
{
this.base64Encode = base64Encode;
this.html = html;
this.charSet = charSet;
}
/// <summary>
/// The html as a Data Uri encoded string
/// </summary>
/// <returns>data Uri string suitable for passing to <see cref="IWebBrowser.Load(string)"/></returns>
public string ToDataUriString()
{
var dataUriString = "data:text/html";
if (!string.IsNullOrEmpty(charSet))
{
dataUriString += ";charset=" + charSet;
}
if (base64Encode)
{
var base64EncodedHtml = Convert.ToBase64String(Encoding.UTF8.GetBytes(html));
return dataUriString + ";base64," + base64EncodedHtml;
}
var uriEncodedHtml = Uri.EscapeDataString(html);
return dataUriString + "," + uriEncodedHtml;
}
/// <summary>
/// HtmlString that will be base64 encoded
/// </summary>
/// <param name="html">raw html (not already encoded)</param>
public static explicit operator HtmlString(string html)
{
return new HtmlString(html, true);
}
/// <summary>
/// Creates a HtmlString for the given file name
/// Uses <see cref="File.ReadAllText(string, Encoding)"/> to read the
/// text using <see cref="Encoding.UTF8"/> encoding.
/// </summary>
/// <param name="fileName">file name</param>
/// <returns>HtmlString</returns>
public static HtmlString FromFile(string fileName)
{
var html = File.ReadAllText(fileName, Encoding.UTF8);
return (HtmlString)html;
}
}
}