How to print to network printer through application hosted in IIS

主宰稳场 提交于 2019-12-12 02:32:33

问题


I have scenario of printing pdf (generated from stream) to network printer through application hosted in IIS. I tried with PrintDocument.Print() and problem I'm facing is: 1. Document is getting queued to the print job queue with size 0 bytes. 2. Document is getting queued to the print job queue with owner name as machine_name. Here is the code which i tried using PdfiumViewer (to generate PrintDocument from bytearray) and System.Drawing.Printing.PrintDocument:

 public void SendPdfToPrinter(byte[] byteArray, string fileName, string printerNetworkPath)
    {
        using (Stream fileStream = new MemoryStream(byteArray)) //byte array for the file content
        {

            var printerSettings = new System.Drawing.Printing.PrinterSettings
            {
                PrinterName = printerNetworkPath, //this is the printer full name. i.e. \\10.10.0.12\ABC-XEROX-01
                PrintFileName = fileName, //file name. i.e. abc.pdf
                PrintRange = System.Drawing.Printing.PrintRange.AllPages,
            };
            printerSettings.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(0, 0, 0, 0);

            // Now print the PDF document
            using (PdfiumViewer.PdfDocument document = PdfiumViewer.PdfDocument.Load(fileStream))
            {
                using (System.Drawing.Printing.PrintDocument printDocument = document.CreatePrintDocument())
                {
                    printDocument.DocumentName = fileName;
                    printDocument.PrinterSettings = printerSettings;
                    printDocument.PrintController = new System.Drawing.Printing.StandardPrintController();
                    printDocument.Print();
                }
            }

回答1:


For both the problems, answer is impersonating the user to do the printing.

In my case app pool is running under LocalSystem account which is obviously is not a domain user and printer is exposed to the domain user only.

Note: Application pool is 64bit, if you use 32bit you will face another set of challenges which is well described here: https://blogs.msdn.microsoft.com/winsdk/2015/05/19/printing-successfully-using-impersonation-from-a-32-bit-application-on-a-64-bit-system/

Below is code which required to do the impersonation for domain user:

 [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonation : IDisposable
{
    private readonly SafeTokenHandle _handle;
    private readonly WindowsImpersonationContext _context;
    bool disposed = false;

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

    public Impersonation(ImpersonateUserDetails user) : this(user.Domain, user.UserName, user.Password)
    { }
    public Impersonation(string domain, string username, string password)
    {
        var ok = LogonUser(username, domain, password,
                       LOGON32_LOGON_INTERACTIVE, 0, out this._handle);
        if (!ok)
        {
            var errorCode = Marshal.GetLastWin32Error();
            throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
        }

        this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle());
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            this._context.Dispose();
            this._handle.Dispose();
        }           
        disposed = true;
    }

    ~Impersonation()
    {
        Dispose(false);
    }


    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

    sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true) { }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }
}

public class ImpersonateUserDetails
{
    public string UserName { get; set; }

    public string Password { get; set; }

    public string Domain { get; set; }
}



回答2:


Another possible & easy solution is to configure your Application Pool Identity to a custom/domain user which has access/permission to print in network printers.



来源:https://stackoverflow.com/questions/43363033/how-to-print-to-network-printer-through-application-hosted-in-iis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!