3

I'm doing some work with HTML and I want to print (on paper) these HTML files, in reality, the file does not exist, everything is saved in a string, all text in HTML, but I would like to print, already formatted...

for example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string HTML =
"<html>" +
"<head>" +
"    <style type=\"text/css\">" +
"    .title {" +
"        color: blue;" +
"        text-decoration: bold;" +
"        text-size: 1em;" +
"    }" +
"    .author {" +
"        color: gray;" +
"    }" +
"    </style>" +
"</head>" +
"<body>" +
"    <p>" +
"    <span class=\"title\">{0}</span>" +
"    <span class=\"author\">{1}</span>" +
"    </p>" +
"</body>" +
"</html>";

            // Just a sample of what I whant to do...
            // PseudoCode
            //Render the HTML code
            RenderHTML aa = new RenderHTML(string.Format(HTML, "Alexandre", "Bencz"));
            aa.PrintDocumentInPaper();
        }
    }
}

I found that: http://msdn.microsoft.com/en-us/library/w290k23d.aspx

But, I whant to know if have another way to do this, a more better way.. ?

2
  • 1
    See this post: stackoverflow.com/questions/2593147/…. It recommends using an HtmlTidy wrapper to do all the formatting and then print it.
    – Marcel N.
    Jan 2, 2013 at 0:50
  • I understand this is probably just some sample code, but I would recommend using the @ operator at the start of the string to signify it as a string literal, which will allow you use avoid all of the concatenation. That, or if you are concatenating the data, make sure you're using a StringBuilder. Best of luck! Jan 2, 2013 at 3:02

1 Answer 1

1

You were on the right track with the webbrowser MSDN class, and I think you can do this quite easily.

1) You'll need to populate its document content via a Stream (of your text string), not a saved file. http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documentstream%28v=vs.100%29.aspx

2) Then simply fire the Print function http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.print%28v=vs.100%29.aspx

p.s. with the links I've provided, I've assumed you're using .Net 4.0.

Not the answer you're looking for? Browse other questions tagged or ask your own question.