简体   繁体   English

在C#中打印文档

[英]Printing a document in C#

I am trying to print a document with .txt extension and for that I am referring to my course book but confused. 我正在尝试打印扩展名为.txt的文档,为此,我指的是我的课程表,但感到困惑。 Here is the source code given in the book : 这是书中给出的源代码:

private void Print_Click(object sender, EventArgs e)
{
printDialog1.Document = printDocument1 // there is no object in my program names ad printDocument1
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
printDocument1.Print();

and there is lot more code given 还有更多的代码

Your example is assuming that a PrintDocument object has been dragged onto the form from the toolbox: you could though just as easily create the object yourself. 您的示例假设已将PrintDocument对象从工具箱拖动到表单上:尽管可以轻松地自己创建对象。

      private void Print_Click(object sender, EventArgs e)
      {
        PrintDocument printDocument = new PrintDocument();
        printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);

        PrintDialog printDialog = new PrintDialog 
        {
            Document = printDocument
        };

        DialogResult result = printDialog.ShowDialog();

        if (result == DialogResult.OK)
        {
            printDocument.Print(); // Raises PrintPage event
        }
    }

    void printDocument_PrintPage(object sender, PrintPageEventArgs e)
    {
        e.Graphics.DrawString(...);
    }

Open the form in design mode. 在设计模式下打开表单。 Locate the PrintDocument control in the toolbox. 在工具箱中找到PrintDocument控件。 Drag and drop it onto your form. 将其拖放到您的窗体上。 That adds a field to your form class named "printDocument1". 这会将一个字段添加到名为“ printDocument1”的表单类中。 Next, double-click the printDocument1 image displayed below the form. 接下来,双击显示在表单下方的printDocument1图像。 That adds the PrintPage event handler. 这将添加PrintPage事件处理程序。 Use the code from your book. 使用书中的代码。

Review the instructions in the book, it should have mentioned this. 阅读书中的说明,应该已经提到了这一点。 Best to use its step-by-step instructions rather than mine. 最好使用其分步说明而不是我的指导。

If you want to print an existing .txt file, you can have Windows print it: 如果要打印现有的.txt文件,则可以让Windows打印该文件:

using System.Diagnostics;

Process myProcess = new Process();
myProcess.StartInfo.FileName = "C:\\thefile.txt";  // adjust to your needs
myProcess.StartInfo.Verb = "print";
myProcess.Start();

See Process . 请参阅流程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM