buba
buba

Reputation: 59

print txt file direct to printer aspx.net

i'm using following method to create txt file, and now I don't know how to send this file direct to printer.I want when user click on button_click event, txt file to be printed without print preview...etc.application is web deployed

 public void Print()
   {

    string path = @"c:\Restaurant\kitchen.txt";


    if (!File.Exists(path))
    {
        using (StreamWriter sw = File.CreateText(path))
        {



                if (Label53.Text == "4")
                {
                  String s = Label47.Text;

                   s = String.Format(s.Replace("S", "С").Replace("U", "У").Replace("P", "П").Replace("A", "А"));


                    sw.WriteLine(s);



                }
             }
          }
        }

Upvotes: 1

Views: 2584

Answers (1)

mybirthname
mybirthname

Reputation: 18127

Yes it is possible...

First you to add Reference System.Drawing to the project.After that you need to use:

using System.Drawing;
using System.Drawing.Printing;

I will show it for console application, you can convert it to asp.net easily.

    [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
    private static extern IntPtr GetStockObject(int fnObject);

    private static string stringToPrint;

    static void Main(string[] args)
    {
        PrintDocument doc = new PrintDocument();
        ReadFile(doc);
        doc.PrintPage += doc_PrintPage;
        doc.Print();
    }

    private static void ReadFile(PrintDocument printDocument1)
    {
        string docName = "Test.txt";
        string docPath = @"c:\";
        printDocument1.DocumentName = docName;
        using (FileStream stream = new FileStream(docPath + docName, FileMode.Open))
        using (StreamReader reader = new StreamReader(stream))
        {
            stringToPrint = reader.ReadToEnd();
        }
    }

    static void doc_PrintPage(object sender, PrintPageEventArgs e)
    {
        int charactersOnPage = 0;
        int linesPerPage = 0;

        // Sets the value of charactersOnPage to the number of characters  
        // of stringToPrint that will fit within the bounds of the page.
        e.Graphics.MeasureString(stringToPrint, Font.FromHfont(GetStockObject(0)),
            e.MarginBounds.Size, StringFormat.GenericTypographic,
            out charactersOnPage, out linesPerPage);

        // Draws the string within the bounds of the page
        e.Graphics.DrawString(stringToPrint, Font.FromHfont(GetStockObject(0)), Brushes.Black,
            e.MarginBounds, StringFormat.GenericTypographic);

        // Remove the portion of the string that has been printed.
        stringToPrint = stringToPrint.Substring(charactersOnPage);

        // Check to see if more pages are to be printed.
        e.HasMorePages = (stringToPrint.Length > 0);
    }

This was the code. I'm using GetStockObject just to create Font you can use another custom Font, if you want.

Upvotes: 2

Related Questions