Thursday, November 15, 2012

How to print a PDF file inside your Windows applicaiton

I have shown you how to export report's output to PDF file using SSRS service the other day.  You now have PDF files generated by this service, but what if you want to print one of these PDF files programmatically inside your Windows applicaiton?

This can be easily done by using the acrobat reader, which is already residing in user's PC.

Here is the source code of actual procedure that I am using in a couple of my projects, and this is how it works.

  1. You call this static procedure with three input parameters
  2. The procedure creates a new process and runs the acrobat reader with the file
  3. The acrobat reader is open in a hidden mode and prints the file
  4. The process waits for a certain time before it is killed.

For the input parameter "acrobatFullPath," my suggestion is to code a small function to get a full path of user's acrobat reader in user's PC.
Otherwise, you probably can use this hardcoded value for that parameter.
C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe
Also, inside my application, I gave 30 seconds to "timeBeforeClosing" parameter.

Please feel free to copy & modify.

// prints a given PDF file using user's Acrobat Reader
public static void PrintPDFUsingAcrobatReader(string acrobatFullPath, int timeBeforeClosing, string fileToBePrinted)
            // create a new process
            Process proc = new Process();
                proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                proc.StartInfo.Verb = "print";

                proc.StartInfo.FileName = acrobatFullPath;
                proc.StartInfo.Arguments = @"/p /h " + fileToBePrinted;
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.CreateNoWindow = true;

                proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                if (proc.HasExited == false)
                    proc.WaitForExit(timeBeforeClosing * 1000);

                proc.EnableRaisingEvents = true;
            catch (Exception e)
                throw e;
                proc = null;

No comments: