OhBeWise
OhBeWise

Reputation: 5454

How do I render special characters in HTML the same in WPF as in Winforms?

I'm working on an email notification project, where in a preexisting Winforms screen the client can edit an email template - adding html, text, etc. A very simplified example input:

<!DOCTYPE html> 
<html>
    <head>
        <title>The Title</title>
    </head>

    <body bgcolor="#f2f2f2" style="margin: 0; padding: 0;">
        <br />
            <b>Please do not respond to this e-mail, as it is not monitored.</b>
        <br/>
        <br/>
            “Foo bar baz.
        <br/>
        <br/>
            Baz bar foo.”
        <br/>
    </body>
</html>

This is saved as a string. On the same screen, the user may then click a button which will raise a ShowDialog call on another Form. This form previews the user's html in a WebBrowser control:

this.webBrowser.DocumentText = theHtmlString;

And the results:

Winforms WebBrowser

Problem:

I am creating a WPF screen related to the Winforms screens mentioned. It too needs the ability to preview the user's html. To do so I've used an attached behavior modified from this version. Essentially, this dialog also previews the user's html in a WebBrowser control:

webBrowser.NavigateToString(theHtmlString);

However, the results aren't correct, as highlighted below:

WPF WebBrowser

If this were my own html input, I'd simply remove the offending characters and replace them with standard quotations. But since this input is from the client, how do I get WPF to render the same as Winforms?

The reason this poses an issue:

  1. In the old Winforms screen, the user creates/edits-existing email templates, previews them, is satisfied with the rendered example, saves changes.
  2. In the new WPF screen, the user exports/imports existing email templates, previews them, is dissatisfied with the rendered example and strange characters, becomes confused when the other screen still renders correctly - calls to report a "bug" in the new screen.

Simple Reproduction Example: - Credit to Eser

var encoded = WebUtility.HtmlEncode(" “ Test ” ");             //" “ Test ” "
var buf = Encoding.UTF8.GetBytes(" “ Test ” "); 
var str = Encoding.GetEncoding("Windows-1252").GetString(buf); //" “ Test †"

Upvotes: 0

Views: 1587

Answers (1)

Dax Pandhi
Dax Pandhi

Reputation: 853

Just add this meta tag to the <head> of your HTML:

<meta charset='utf-8'>

This will display the special characters correctly. I just tested your exact code with this and it works.

Upvotes: 1

Related Questions