[Skip to Content]

Published Tuesday 21 December 2010
Categories: Projects |

Post View Counter 282

The code below allows you to print pdf documents which are on a web server to an attached or network printer. Under IIS 7 I found that you need to setup a user account with permisisons for Acrobat Reader and printing which is then assigned to the Application Pool for the website. If you don't do this you will spend hours trying to figure out why your code won't print!

Written with help from a lot of blogs, forums and support pages.

<%@ Page Language="C#"%>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace = "System.Web" %>
<%@ Import Namespace = "System.Web.Security" %>
<%@ Import Namespace = "System.Security.Principal" %>
<%@ Import Namespace = "System.Runtime.InteropServices" %>

<script runat="server"%>
  
protected void Page_Load(Object Src, EventArgs E)
{
   // pass file name within site root via file querystring
   printpdf(Request.QueryString["file"];

}


 public const int LOGON32_LOGON_INTERACTIVE = 2;
 public const int LOGON32_PROVIDER_DEFAULT = 0;

 WindowsImpersonationContext impersonationContext;

 [DllImport("advapi32.dll")]
 public static extern int LogonUserA(String lpszUserName,
     String lpszDomain,
     String lpszPassword,
     int dwLogonType,
     int dwLogonProvider,
     ref IntPtr phToken);
 [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
 public static extern int DuplicateToken(IntPtr hToken,
     int impersonationLevel,
     ref IntPtr hNewToken);

 [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
 public static extern bool RevertToSelf();

 [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
 public static extern bool CloseHandle(IntPtr handle);


 private bool impersonateValidUser(String userName, String domain, String password)
 {
     WindowsIdentity tempWindowsIdentity;
     IntPtr token = IntPtr.Zero;
     IntPtr tokenDuplicate = IntPtr.Zero;

     if (RevertToSelf())
     {
         if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
             LOGON32_PROVIDER_DEFAULT, ref token) != 0)
         {
             if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
             {
                 tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                 impersonationContext = tempWindowsIdentity.Impersonate();
                 if (impersonationContext != null)
                 {
                     CloseHandle(token);
                     CloseHandle(tokenDuplicate);
                     return true;
                 }
             }
         }
     }
     if (token != IntPtr.Zero)
         CloseHandle(token);
     if (tokenDuplicate != IntPtr.Zero)
         CloseHandle(tokenDuplicate);
     return false;
 }

 private void undoImpersonation()
 {
     impersonationContext.Undo();
 }

 public void printpdf(string filepath)
    {
        // enter your computer username, computer name and password
        if (impersonateValidUser("Username", "Computername", "Password"))
        {
         ProcessStartInfo startInfo = new ProcessStartInfo();
        // enter the path to adobe acrobat reader
        startInfo.FileName =  @"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe";
        // replace \"Samsung CLP-310 Series\" 10.0.0.50 with the printer name and port
        string args = "/t \"" + Server.MapPath(filepath) + "\" \"\"Samsung CLP-310 Series\" 10.0.0.50\"";
        startInfo.Arguments = args;
        startInfo.CreateNoWindow = true;
        startInfo.ErrorDialog =  false;
        startInfo.UseShellExecute = false;
        // enter the folder path to adobe acrobat reader
        startInfo.WorkingDirectory =  @"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\";
        Process process = Process.Start(startInfo);
        if (!process.WaitForExit(5000)){
        // Kill Adobe Reader/Acrobat
         process.Kill();
         }
            undoImpersonation();
            Label1.Text = "The invoice was printed.";
        }
        else
        {
            // user login failed
            Label1.Text = "The invoice failed to login and print.";
        }
    }


Permalink


0 Comments



Post your comment