c++

C# – printing a note pad text file

c++

i am trying to print this document but only gives me a blank page.
i have checked the Password.txt File is not empty so i dont know why its printing out a blank page . this is C# coding

private void button6_Click(object sender, EventArgs e){    StreamReader Printfile = new StreamReader("c:\\testDir1\\Password.txt);    try    {        PrintDocument docToPrint = new PrintDocument();        docToPrint.DocumentName = "Password";        printDialog1.AllowSomePages = true;        printDialog1.ShowHelp = true;        printDialog1.Document = docToPrint;        DialogResult result = printDialog1.ShowDialog();        printPreviewDialog1.Document = docToPrint;        printPreviewDialog1.ShowDialog();        Printfile.Close();        if (result == DialogResult.OK)        {            docToPrint.Print();            MessageBox.Show("Printing file");        }    }    catch (System.Exception f)    {        MessageBox.Show(f.Message);    }    finally    {        Printfile.Close();    }}

Best Solution

The PritnDocument will fire the PrintPage event for every page that needs to be printed. You can hook into that event and "Draw" your page. In your case, draw a string for every line in the text file.

Font printFont = new Font("Arial", 10);StreamReader Printfile;private void button6_Click(object sender, EventArgs e){    using(StreamReader Printfile = new StreamReader("c:\\testDir1\\Password.txt")) //file path     {        try        {            PrintDocument docToPrint = new PrintDocument();            docToPrint.DocumentName = "Password"; //Name that appears in the printer queue            docToPrint.PrintPage += (s, ev) =>            {                float linesPerPage = 0;                float yPos = 0;                int count = 0;                float leftMargin = ev.MarginBounds.Left;                float topMargin = ev.MarginBounds.Top;                string line = null;                // Calculate the number of lines per page.                linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);                // Print each line of the file.                 while (count < linesPerPage && ((line = Printfile.ReadLine()) != null))                {                    yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));                    ev.Graphics.DrawString(line, printFont, Brushes.Black,  leftMargin, yPos, new StringFormat());                    count++;                }                // If more lines exist, print another page.                 if (line != null)                    ev.HasMorePages = true;                else                    ev.HasMorePages = false;            };            docToPrint.Print();        }        catch (System.Exception f)        {            MessageBox.Show(f.Message);        }    }}