如何打印在C#中使用PrintDialog类的文本文件

时间:2019-02-01 14:03:48

标签: c#

我是C# Windows窗体的新手。

我试图打印使用的文本文件的内容的PrintDialog如屏幕截图所示。

Screenshot

以下代码正常工作并且正在打印,但是无需打开PrintDialog即可立即进行打印过程。我想打开PrintDialog因为我有3台打印机,我想选择一个特定的打印机,当我点击OK我要打印出来。

任何人都知道如何修改此代码,以便它可以显示PrintDialog框,以便我可以选择打印机并继续打印?。

 private void Print_Click(object sender, EventArgs e)
        {
        string filename = @"D:\\File1.txt";
        //Create a StreamReader object  
        reader = new StreamReader(filename);
        //Create a Verdana font with size 10  
        verdana10Font = new Font("Verdana", 10);
        //Create a PrintDocument object  
        PrintDocument pd = new PrintDocument();
        //Add PrintPage event handler  
        pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
        //Call Print Method  
        pd.Print();
        //Close the reader  
        if (reader != null)
            reader.Close();

        }



    private void PrintTextFileHandler(object sender, PrintPageEventArgs ppeArgs)
        {
        //Get the Graphics object  
        Graphics g = ppeArgs.Graphics;
        float linesPerPage = 0;
        float yPos = 0;
        int count = 0;
        float leftMargin = 0;



        float topMargin = 50;
        string line = null;
        //Calculate the lines per page on the basis of the height of the page and the height of the font  
        linesPerPage = ppeArgs.MarginBounds.Height / verdana10Font.GetHeight(g);
        //Now read lines one by one, using StreamReader  
        while (count < linesPerPage && ((line = reader.ReadLine()) != null))
            {
            //Calculate the starting position  
            yPos = topMargin + (count * verdana10Font.GetHeight(g));
            //Draw text  
            g.DrawString(line, verdana10Font, Brushes.Black, leftMargin, yPos, new StringFormat());
            //Move to next line  
            count++;
            }
        //If PrintPageEventArgs has more pages to print  
        if (line != null)
            {
            ppeArgs.HasMorePages = true;
            }
        else
            {
            ppeArgs.HasMorePages = false;
            }


        }

1 个答案:

答案 0 :(得分:1)

您可以使用PrintDialog这样做。

PrintDialog pdialog = new PrintDialog();
pdialog.Document = pd;
if (pdialog.ShowDialog() == DialogResult.OK)
{
    pd.Print();
}

完整代码

PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
PrintDialog pdialog = new PrintDialog();
pdialog.Document = pd;
if (pdialog.ShowDialog() == DialogResult.OK)
{
    pd.Print();
}