从ASP.NET打印到网络打印机

我需要将文件发送到网络打印机(\ myserver \ myprinter)。 我正在使用System.Printing类进行打印,当它来自Windows服务时工作正常,但是从ASP.NET应用程序中,它只能打印到本地打印机,而不能打印到网络打印机。 我得到的错误是“打印机名称无效”这是我用来获取打印机名称:

public string PrinterName { using (LocalPrintServer server = new LocalPrintServer()) return server.GetPrintQueue(@"\\myserver\myprinter"); } 

我有什么选择? 这是权限问题吗?

您可以通过模拟或提升运行Web应用程序的用户的权限来解决凭据问题。

但是,我们通过在服务器上添加网络打印机作为打印机(在服务器上添加打印机对话框)并将作业发送到该打印机来实现。

我们像这样使用Printing.PrintDocument(VB中的代码)….

 Public Class SpecialReportPrintJob Inherits Printing.PrintDocument Protected Overrides Sub OnBeginPrint(ByVal ev as Printing.PrintEventArgs) MyBase.OnBeginPrint(ev) Me.PrinterSettings.PrinterName = "PrinterNameUsedOnServer" 'setup rest of stuff.... End Sub End Class 'And we then call it like so Dim printSpecialReport as new SpecialReportPrintJob() printSpecialReport.Print() 

默认情况下,ASP.NET应用程序在具有有限权限的特殊帐户上运行。 刚刚足以提供网页服务,仅此而已。 所以你必须配置ASPNET用户。

相比之下,Windows服务通常在本地系统帐户下运行(具有高权限)

ASP.Net/C#中的网络打印可以使用以下方式完成:

如果为域用户配置了网络,则将打印机添加到打印服务器:

  • PrinterName定义为=“\\ PrintServerIP_OR_Name \\ PRINTERNAME”示例:PrinterSettings.PrinterName =“\\ 15.1.1.1 \\ prn001”
  • 检查打印机访问权限上设置的权限
  • 无论是域用户还是每个人
  • 如果是域用户,那么C#代码可以包含在可用于调用打印代码的模拟中,如下所示:
 ///  /// Does the actual impersonation. ///  /// The name of the user to act as. /// The domain name of the user to act as. /// The password of the user to act as. private void ImpersonateValidUser( string userName, string domain, string password ) { WindowsIdentity tempWindowsIdentity = null; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; try { if ( RevertToSelf() ) { if ( LogonUser( 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(); } else { throw new Win32Exception( Marshal.GetLastWin32Error() ); } } else { throw new Win32Exception( Marshal.GetLastWin32Error() ); } } else { throw new Win32Exception( Marshal.GetLastWin32Error() ); } } finally { if ( token!= IntPtr.Zero ) { CloseHandle( token ); } if ( tokenDuplicate!=IntPtr.Zero ) { CloseHandle( tokenDuplicate ); } } } ///  /// Reverts the impersonation. ///  private void UndoImpersonation() { if ( impersonationContext!=null ) { impersonationContext.Undo(); } } private WindowsImpersonationContext impersonationContext = null; 

首先调用模拟用户,然后调用如下所示的print函数:

 if(ImpersonateValidUser("username", "domain", "password")) { PrintDetails(); UndoImpersonation(); }