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
6
  • What problem are you running into? I'd think that sticking all of the appropriate characters into a string would work, but maybe not? Commented Feb 10, 2011 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? Commented Feb 10, 2011 at 19:41
  • Unfortunately it does not work like that. I really don't know what direction to go from here... Commented Feb 10, 2011 at 19:42
  • In what context? Are you saying you want to fetch and/or display dynamically generated HTML content? Commented Feb 10, 2011 at 19:44
  • I simply want to go from a C# string to a properly rendered HTML printout Commented Feb 10, 2011 at 19:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can I go from a C# string directly to WebBrowserControl print without writing a separate file?
@sooprise - I didn't try this myself, but you should be able to use the DocumentStream directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.