Wednesday, 19 July 2006

Print PDF from command line and make Acrobat go away

Some C# code that this "hack developer" of a DBA put together. Put in a console app in Visual Studio. When executing the compiled program just pass the full path and filename as the argument. One bug that's surfaced already is that it doesn't like mapped drives, but UNC paths work fine. Otherwise … enjoy !!!

    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.ComponentModel;

    namespace PDFPrinter
    {
    class PDFPrinter
    {
    [STAThread]
    static void Main(string[] args)
    {
    if(args.Length > 0)
    {
    try
    {
    Process myProcess = new Process();
    myProcess.StartInfo.Verb = "Print";
    myProcess.StartInfo.CreateNoWindow = true;
    myProcess.StartInfo.FileName = args[0].ToString();
    myProcess.Start();
    myProcess.WaitForInputIdle();
    Thread.Sleep(5000);
    if(!myProcess.CloseMainWindow())
    {
    myProcess.Kill();
    }
    }
    catch (Exception ex)
    {
    string excepMsg = "";
    Exception current = ex;

    while( current != null)
    {
    excepMsg = current.Message;
    current = current.InnerException;
    }
    Console.WriteLine(excepMsg);
    }
    }
    else
    {
    Console.WriteLine("You need to specify the name of the PDF file to print.");
    }
    }
    }
    }

No comments: