Khan Shahrukh
Khan Shahrukh

Reputation: 6401

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. 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

Upvotes: 2

Views: 4776

Answers (3)

stuartd
stuartd

Reputation: 73303

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.

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

Upvotes: 3

Hans Kesting
Hans Kesting

Reputation: 39338

If you want to print an existing .txt file, you can have Windows print it:

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.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 942197

Open the form in design mode. Locate the PrintDocument control in the toolbox. Drag and drop it onto your form. That adds a field to your form class named "printDocument1". Next, double-click the printDocument1 image displayed below the form. That adds the PrintPage event handler. 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.

Upvotes: 1

Related Questions