imprimir c#

6
Más información Para enviar datos sin formato a una impresora de Microsoft .NET Framework, el programa debe trabajar con funciones de la cola de impresión 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 continuación, usar fuentes transferibles. Enviar a la cola de impresión archivos preimpresos. Para enviar a una impresora éstos y otros tipos de datos sin formato, el código debe poder usarse con las interfaces de programación de aplicaciones (API) de cola de impresión Win32. El código siguiente muestra cómo leer el contenido de un archivo con formato previo en memoria y, a continuación, enviar esos bytes a la impresora mediante WritePrinter . Nota : no puede utilizar este enfoque en el mismo trabajo de impresión como un trabajo de impresión PrintDocument nativo. Debe usar .NET Framework para imprimir o bien enviar los bytes del trabajo de impresión. Volver al principio Crear un proyecto que imprime datos con formato previo 1. Inicie Visual Studio NET.. En el menú archivo , haga clic en nuevo y, a continuación, haga clic en proyecto . En Tipos de proyecto , haga clic en la carpeta Proyectos de Visual C# . En la lista de plantillas , haga clic en Aplicación para Windows y, a continuación, haga clic en Aceptar . De forma predeterminada, se crea Form1. 2. En el menú Ver , haga clic en cuadro de herramientas para mostrar el cuadro de herramientas y, a continuación, agregue un botón a Form1. El botón se llama Button1. 3. Agregue otro botón a Form1. Este botón se denomina Button2. 4. Haga doble clic en Button1 . Aparece la ventana de código del formulario. 5. Reemplace la subrutina Button1_Click con el siguiente código: 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.

Upload: reynaldo-quispe

Post on 22-Feb-2015

180 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: imprimir c#

Más información

Para enviar datos sin formato a una impresora de Microsoft .NET Framework, el programa debe trabajar con funciones de la cola de impresión 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 continuación, usar fuentes transferibles. Enviar a la cola de impresión archivos preimpresos.

Para enviar a una impresora éstos y otros tipos de datos sin formato, el código debe poder usarse con las interfaces de programación de aplicaciones (API) de cola de impresión Win32. El código siguiente muestra cómo leer el contenido de un archivo con formato previo en memoria y, a continuación, enviar esos bytes a la impresora mediante WritePrinter . 

Nota : no puede utilizar este enfoque en el mismo trabajo de impresión como un trabajo de impresión PrintDocument nativo. Debe usar .NET Framework para imprimir o bien enviar los bytes del trabajo de impresión. 

Volver al principio

Crear un proyecto que imprime datos con formato previo

1. Inicie Visual Studio NET.. En el menú archivo , haga clic en nuevo y, a continuación, haga clic en proyecto . En Tipos de proyecto , haga clic en la carpeta Proyectos de Visual C# . En la lista de plantillas , haga clic en Aplicación para Windows y, a continuación, haga clic en Aceptar . De forma predeterminada, se crea Form1.

2. En el menú Ver , haga clic en cuadro de herramientas para mostrar el cuadro de herramientas y, a continuación, agregue un botón a Form1. El botón se llama Button1.

3. Agregue otro botón a Form1. Este botón se denomina Button2.4. Haga doble clic en Button1 . Aparece la ventana de código del formulario.5. Reemplace la subrutina Button1_Click con el siguiente código: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. }

Page 2: imprimir c#

22. Reemplace la subrutina Button2_Click con el siguiente código: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. }

36. Inserte el código siguiente al principio del archivo:37. using System;38. using System.Drawing;39. using System.Drawing.Printing;40. using System.Windows.Forms;41. using System.Runtime.InteropServices;

42. Agregue el código siguiente dentro del espacio de nombres aplicación principal pero fuera de las definiciones de clase:

43. public class RawPrinterHelper44. {45. // Structure and API declarions:46. [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]47. public class DOCINFOA48. {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);

Page 3: imprimir c#

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

array76. // 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.

Page 4: imprimir c#

95. if( StartPagePrinter(hPrinter) )96. {97. // Write your bytes.98. bSuccess = WritePrinter(hPrinter, pBytes,

dwCount, out dwWritten);99. EndPagePrinter(hPrinter);100. }101. EndDocPrinter(hPrinter);102. }103. ClosePrinter(hPrinter);104. }105. // If you did not succeed, GetLastError may give more

information106. // 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. {

Page 5: imprimir c#

142. IntPtr pBytes;143. Int32 dwCount;144. // How many characters are in the string?145. dwCount = szString.Length;146. // Assume that the printer is expecting ANSI text, and

then convert147. // the string to ANSI text.148. pBytes = Marshal.StringToCoTaskMemAnsi(szString);149. // Send the converted ANSI string to the printer.150. SendBytesToPrinter(szPrinterName, pBytes, dwCount);151. Marshal.FreeCoTaskMem(pBytes);152. return true;153. }154. }

155. Presione F5 para generar el programa y a continuación ejecútelo.156. Haga clic en Button1 para cargar e imprimir el contenido del archivo.157. Haga clic en Button2 para imprimir una cadena. (Quizás tenga que retirar la página

manualmente porque la cadena se envía sin el comando formfeed .)