Code to Print Simple Text from .NET
Microsoft provides a KB article called:
HOW TO: Send Raw Data to a Printer by Using Visual C# .NET
http://support.microsoft.com/?kbid=322091
The code works great but requires a bit of tweaking (code does not automatically wrap text beyond the width of the page). Also, you have to pass in the ‘full name’ of a locally configured printer (this does not have to be a locally _connected_ printer) to print.
I wrote the following code segment to print a XML document. This code will format the XML text and line wrap … so you don’t have this hugh jumble of text.
public static bool SendXmlDocumentToPrinter( string szPrinterName, XmlDocument xd )
{
System.IO.MemoryStream mem = new System.IO.MemoryStream();
XmlTextWriter w = new XmlTextWriter(mem, System.Text.Encoding.ASCII);
w.Indentation = 4;
w.Formatting = System.Xml.Formatting.Indented;
XmlNodeReader nodeReader = new XmlNodeReader(xd);
while (nodeReader.Read())
{
w.WriteNode(nodeReader, true);
}
w.Flush();
mem.Position = 0;
System.IO.StreamReader sr = new System.IO.StreamReader(mem);
string s = sr.ReadToEnd();
foreach (string ss in s.Split(‘\r’))
{
string newSS = ss.Clone().ToString();
if (newSS.Length > 78)
{
for (int i = 1; i*78 < ss.Length; i++)
{
newSS = newSS.Insert(i*78, “\r\n”);
}
}
s = s.Replace(ss, newSS);
}
RawPrinterHelper.SendStringToPrinter(szPrinterName, s);
return true;
}