0

我正在尝试打印此文档,但只给了我一个空白页。我检查了 Password.txt 文件不是空的,所以我不知道为什么它打印出一个空白页。这是 C# 编码

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();
    }
}
4

1 回答 1

2

PritnDocument 将为需要打印的每个页面触发 PrintPage 事件。您可以挂钩该事件并“绘制”您的页面。在您的情况下,为文本文件中的每一行绘制一个字符串。

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);
        }
    }
}
于 2013-08-17T09:43:16.397 回答