Search code examples
c#winformspdf.net-4.0printing

How can I send a file document to the printer and have it print?


Here's the basic premise:

My user clicks some gizmos and a PDF file is spit out to his desktop. Is there some way for me to send this file to the printer queue and have it print to the locally connected printer?

string filePath = "filepathisalreadysethere";
SendToPrinter(filePath); //Something like this?

He will do this process many times. For each student in a classroom he has to print a small report card. So I generate a PDF for each student, and I'd like to automate the printing process instead of having the user generated pdf, print, generate pdf, print, generate pdf, print.

Any suggestions on how to approach this? I'm running on Windows XP with Windows Forms .NET 4.

I've found this StackOverflow question where the accepted answer suggests:

Once you have created your files, you can print them via a command line (you can using the Command class found in the System.Diagnostics namespace for that)

How would I accomplish this?


Solution

  • You can tell Acrobat Reader to print the file using (as someone's already mentioned here) the 'print' verb. You will need to close Acrobat Reader programmatically after that, too:

    private void SendToPrinter()
    {
       ProcessStartInfo info = new ProcessStartInfo();
       info.Verb = "print";
       info.FileName = @"c:\output.pdf";
       info.CreateNoWindow = true;
       info.WindowStyle = ProcessWindowStyle.Hidden;
    
       Process p = new Process();
       p.StartInfo = info;
       p.Start();
    
       p.WaitForInputIdle();
       System.Threading.Thread.Sleep(3000);
       if (false == p.CloseMainWindow())
          p.Kill();
    }
    

    This opens Acrobat Reader and tells it to send the PDF to the default printer, and then shuts down Acrobat after three seconds.

    If you are willing to ship other products with your application then you could use GhostScript (free), or a command-line PDF printer such as http://www.commandlinepdf.com/ (commercial).

    Note: the sample code opens the PDF in the application current registered to print PDFs, which is the Adobe Acrobat Reader on most people's machines. However, it is possible that they use a different PDF viewer such as Foxit (http://www.foxitsoftware.com/pdf/reader/). The sample code should still work, though.