Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Para enviar datos sin formato a una impresora de Microsoft .NET Framework, el programa debe trabajar con funciones de la cola de impresin Win32. Mediante .NET Framework, puede imprimir mediante PrintDocument , PrintController y las clases asociadas. Sin embargo, con .NET Framework no puede enviar a una impresora datos con formato previo preparados para imprimir. Puede que tenga que enviar los datos sin formato para hacer lo siguiente:
Enviar secuencias de escape. Descargar y, a continuacin, usar fuentes transferibles. Enviar a la cola de impresin archivos preimpresos.
Para enviar a una impresora stos y otros tipos de datos sin formato, el cdigo debe poder usarse con las interfaces de programacin de aplicaciones (API) de cola de impresin Win32. El cdigo siguiente muestra cmo leer el contenido de un archivo con formato previo en memoria y, a continuacin, enviar esos bytes a la impresora mediante WritePrinter . Nota : no puede utilizar este enfoque en el mismo trabajo de impresin como un trabajo de impresin PrintDocument nativo. Debe usar .NET Framework para imprimir o bien enviar los bytes del trabajo de impresin. Volver al principio
2. 3. 4. 5.
6. private void button1_Click(object sender, System.EventArgs e) 7. { 8. // Allow the user to select a file. 9. OpenFileDialog ofd = new OpenFileDialog(); 10. if( DialogResult.OK == ofd.ShowDialog(this) ) 11. { 12. // Allow the user to select a printer. 13. PrintDialog pd = new PrintDialog(); 14. pd.PrinterSettings = new PrinterSettings(); 15. if( DialogResult.OK == pd.ShowDialog(this) ) 16. { 17. // Print the file to the printer. 18. RawPrinterHelper.SendFileToPrinter(pd.PrinterSettings.PrinterName, ofd.FileName); 19. } 20. } 21. }
23. private void button2_Click(object sender, System.EventArgs e) 24. { 25. string s = "Hello"; // device-dependent string, need a FormFeed? 26. 27. // Allow the user to select a printer. 28. PrintDialog pd = new PrintDialog(); 29. pd.PrinterSettings = new PrinterSettings(); 30. if( DialogResult.OK == pd.ShowDialog(this) ) 31. { 32. // Send a printer-specific to the printer. 33. RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s); 34. } 35. }
37. using 38. using 39. using 40. using 41. using
42. Agregue el cdigo siguiente dentro del espacio de nombres aplicacin principal pero fuera de las definiciones de clase:
43. public class RawPrinterHelper 44. { 45. // Structure and API declarions: 46. [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)] 47. public class DOCINFOA 48. { 49. [MarshalAs(UnmanagedType.LPStr)] public string pDocName; 50. [MarshalAs(UnmanagedType.LPStr)] public string pOutputFile; 51. [MarshalAs(UnmanagedType.LPStr)] public string pDataType; 52. } 53. [DllImport("winspool.Drv", EntryPoint="OpenPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 54. public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd); 55. 56. [DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 57. public static extern bool ClosePrinter(IntPtr hPrinter); 58.
59.
[DllImport("winspool.Drv", EntryPoint="StartDocPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 60. public static extern bool StartDocPrinter( IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di); 61. 62. [DllImport("winspool.Drv", EntryPoint="EndDocPrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 63. public static extern bool EndDocPrinter(IntPtr hPrinter); 64. 65. [DllImport("winspool.Drv", EntryPoint="StartPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 66. public static extern bool StartPagePrinter(IntPtr hPrinter); 67. 68. [DllImport("winspool.Drv", EntryPoint="EndPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 69. public static extern bool EndPagePrinter(IntPtr hPrinter); 70. 71. [DllImport("winspool.Drv", EntryPoint="WritePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 72. public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten ); 73. 74. // SendBytesToPrinter() 75. // When the function is given a printer name and an unmanaged array 76. // of bytes, the function sends those bytes to the print queue. 77. // Returns true on success, false on failure. 78. public static bool SendBytesToPrinter( string szPrinterName, IntPtr pBytes, Int32 dwCount) 79. { 80. Int32 dwError = 0, dwWritten = 0; 81. IntPtr hPrinter = new IntPtr(0); 82. DOCINFOA di = new DOCINFOA(); 83. bool bSuccess = false; // Assume failure unless you specifically succeed. 84. 85. di.pDocName = "My C#.NET RAW Document"; 86. di.pDataType = "RAW"; 87. 88. // Open the printer. 89. if( OpenPrinter( szPrinterName.Normalize(), out hPrinter, IntPtr.Zero ) ) 90. { 91. // Start a document. 92. if( StartDocPrinter(hPrinter, 1, di) ) 93. { 94. // Start a page. 95. if( StartPagePrinter(hPrinter) ) 96. { 97. // Write your bytes.
99. EndPagePrinter(hPrinter); 100. } 101. EndDocPrinter(hPrinter); 102. } 103. ClosePrinter(hPrinter); 104. } 105. // If you did not succeed, GetLastError may give more information 106. // about why not. 107. if( bSuccess == false ) 108. { 109. dwError = Marshal.GetLastWin32Error(); 110. } 111. return bSuccess; 112. } 113. 114. public static bool SendFileToPrinter( string szPrinterName, string szFileName ) 115. { 116. // Open the file. 117. FileStream fs = new FileStream(szFileName, FileMode.Open); 118. // Create a BinaryReader on the file. 119. BinaryReader br = new BinaryReader(fs); 120. // Dim an array of bytes big enough to hold the file's contents. 121. Byte []bytes = new Byte[fs.Length]; 122. bool bSuccess = false; 123. // Your unmanaged pointer. 124. IntPtr pUnmanagedBytes = new IntPtr(0); 125. int nLength; 126. 127. nLength = Convert.ToInt32(fs.Length); 128. // Read the contents of the file into the array. 129. bytes = br.ReadBytes( nLength ); 130. // Allocate some unmanaged memory for those bytes. 131. pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength); 132. // Copy the managed byte array into the unmanaged array. 133. Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength); 134. // Send the unmanaged bytes to the printer. 135. bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength); 136. // Free the unmanaged memory that you allocated earlier. 137. Marshal.FreeCoTaskMem(pUnmanagedBytes); 138. return bSuccess; 139. } 140. public static bool SendStringToPrinter( string szPrinterName, string szString ) 141. { 142. IntPtr pBytes; 143. Int32 dwCount; 144. // How many characters are in the string? 145. dwCount = szString.Length;
146. convert 147. 148. 149. 150. 151. 152. 153. } 154. }
// Assume that the printer is expecting ANSI text, and then // the string to ANSI text. pBytes = Marshal.StringToCoTaskMemAnsi(szString); // Send the converted ANSI string to the printer. SendBytesToPrinter(szPrinterName, pBytes, dwCount); Marshal.FreeCoTaskMem(pBytes); return true;
155. Presione F5 para generar el programa y a continuacin ejectelo. 156. Haga clic en Button1 para cargar e imprimir el contenido del archivo. 157. Haga clic en Button2 para imprimir una cadena. (Quizs tenga que retirar la pgina manualmente porque la cadena se enva sin el comando formfeed .)