3

How can I print an HTML string so all of the HTML tags are recognized and rendered correctly? I imagine it's possible to create a .HTML file and print it, but if there is a way to do this without creating extra files I'd be interested in learning how. Thanks!

Addendum:

pd.PrintPage += new PrintPageEventHandler(PrintDocument_PrintPage);
pd.Print();

More code:

static private void PrintDocument_PrintPage(Object sender, PrintPageEventArgs e) {
    Font printFont = new Font("Courier New", 12);
    e.Graphics.DrawString("<b>Hello</b> world", printFont, Brushes.Black, 0, 0);
}

Printed result:

<b>Hello</b> world
sooprise
  • 22,657
  • 67
  • 188
  • 276
  • What problem are you running into? I'd think that sticking all of the appropriate characters into a `string` would work, but maybe not? – John Feb 10 '11 at 19:40
  • If you output correct HTML, it will be "recognized and rendered correctly". Where are you "printing" to? What are you using to view the HTML? – Oded Feb 10 '11 at 19:41
  • Unfortunately it does not work like that. I really don't know what direction to go from here... – sooprise Feb 10 '11 at 19:42
  • In what context? Are you saying you want to fetch and/or display dynamically generated HTML content? – Robin Maben Feb 10 '11 at 19:44
  • I simply want to go from a C# string to a properly rendered HTML printout – sooprise Feb 10 '11 at 19:45
  • see this [stackoverflow answer](https://stackoverflow.com/questions/174/how-do-i-print-an-html-document-from-a-web-service/768#768), you can also see this [code project article](http://www.codeproject.com/KB/printing/printhml.aspx), in which you can disable print dialog too. – Adeel Feb 10 '11 at 19:50

1 Answers1

4

The Graphics object does not understand HTML, and DrawString will do exactly as requested, as you have found out.

You will need to use the Graphics object with a bold font for Hello and a non bold font for world and remove the HTML markup.

So, for a more general approach, you would need an HTML parser (such as the HTML Agility Pack) and a way to translate the HTML to different fonts.

You may find it easier to use a WebBrowser control and use it to print.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Can I go from a C# string directly to WebBrowserControl print without writing a separate file? – sooprise Feb 10 '11 at 19:56
  • @sooprise - I didn't try this myself, but you should be able to use the [`DocumentStream`](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documentstream.aspx) directly. – Oded Feb 10 '11 at 19:59