C sharp - Impresion de tickets C#

 
Vista:
sin imagen de perfil

Impresion de tickets C#

Publicado por MARCELO (5 intervenciones) el 19/05/2017 05:44:05
Buenas noches:

Quisiera pedir ayuda con un programa que imprime tickets de venta, tengo hecha toda la impresión de tickets pero necesito agregar una imagen de cabecera y un código de barras al final y no se como hacerlo :(, espero me puedan ayudar dejo el código para que lo revisen y por si a alguien le sirve.

Código clase CrearTicket

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Drawing.Printing; using System.Runtime.InteropServices;
 
namespace sistema_compu {
 class CrearTicket {
StringBuilder linea = new StringBuilder();
 
    public string lineasGuio()
    {
        string lineasGuion = "";
        for (int i = 0; i < maxCar; i++)
        {
            lineasGuion += "-";
        }
        return linea.AppendLine(lineasGuion).ToString();
    }
 
    public string lineasAsteriscos()
    {
        string lineasAsterisco = "";
        for (int i = 0; i < maxCar; i++)
        {
            lineasAsterisco += "*";
        }
        return linea.AppendLine(lineasAsterisco).ToString();
    }
 
    public string lineasIgual()
    {
        string lineasIgual = "";
        for (int i = 0; i < maxCar; i++)
        {
            lineasIgual += "=";
        }
        return linea.AppendLine(lineasIgual).ToString();
    }
 
    public void TextoIzquierda(string texto)
    {
        if (texto.Length > maxCar)
        {
            int caracterActual = 0;
            for (int longitudTexto = texto.Length; longitudTexto > maxCar; longitudTexto -= maxCar)
            {
                linea.AppendLine(texto.Substring(caracterActual, maxCar));
                caracterActual += maxCar;
            }
            linea.AppendLine(texto.Substring(caracterActual, texto.Length - caracterActual));
        }
        else
        {
            linea.AppendLine(texto);
        }
    }
 
    public void TextoDerecha(string texto)
    {
        if (texto.Length > maxCar)
        {
            int caracterActual = 0;
            for (int longitudTexto = texto.Length; longitudTexto > maxCar; longitudTexto -= maxCar)
            {
                linea.AppendLine(texto.Substring(caracterActual, maxCar));
                caracterActual += maxCar;
            }
 
            string espacios = "";
 
            for (int i = 0; i < (maxCar - texto.Substring(caracterActual, texto.Length - caracterActual).Length); i++)
            {
                espacios += " ";
            }
 
            linea.AppendLine(espacios + texto.Substring(caracterActual, texto.Length - caracterActual));
        }
        else
        {
            string espacios = "";
            for (int i = 0; i < (maxCar - texto.Length); i++)
            {
                espacios += " ";
            }
            linea.AppendLine(espacios + texto);
        }
    }
 
    public void TextoCentro(string texto)
    {
        if (texto.Length > maxCar)
        {
            int caracterActual = 0;
            for (int longitudTexto = texto.Length; longitudTexto > maxCar; longitudTexto -= maxCar)
            {
                linea.AppendLine(texto.Substring(caracterActual, maxCar));
                caracterActual += maxCar;
            }
 
            string espacios = "";
            int centrar = (maxCar - texto.Substring(caracterActual, texto.Length - caracterActual).Length) / 2;
            for (int i = 0; i < centrar; i++)
            {
                espacios += " ";
            }
 
            linea.AppendLine(espacios + texto.Substring(caracterActual, texto.Length - caracterActual));
        }
        else
        {
            string espacios = "";
 
            int centrar = (maxCar - texto.Length) / 2;
 
            for (int i = 0; i < centrar; i++)
            {
                espacios += " ";
            }
 
            linea.AppendLine(espacios + texto);
 
        }
    }
 
    public void TextoExtremos(string textoIzquierdo, string textoDerecho)
    {
        string textoIzq, textoDer, textoCompleto = "", espacios = "";
 
        if (textoIzquierdo.Length > 22)
        {
            cortar = textoIzquierdo.Length - 22;
            textoIzq = textoIzquierdo.Remove(22, cortar);
        }
        else
        { textoIzq = textoIzquierdo; }
 
        textoCompleto = textoIzq;
 
        if (textoDerecho.Length > 24)
        {
            cortar = textoDerecho.Length - 24;
            textoDer = textoDerecho.Remove(24, cortar);
        }
        else
        { textoDer = textoDerecho; }
 
        int nroEspacios = maxCar - (textoIzq.Length + textoDer.Length);
        for (int i = 0; i < nroEspacios; i++)
        {
            espacios += " ";
        }
        textoCompleto += espacios + textoDerecho;
        linea.AppendLine(textoCompleto);//agregamos la linea al ticket, al objeto en si.
    }
 
    public void EncabezadoVenta()
    {
        linea.AppendLine("ITEM                          |CANT  |PRECIO    ");
    }
 
    public void AgregarTotales(string texto, decimal total)
    {
        string resumen, valor, textoCompleto, espacios = "";
 
        if (texto.Length > 29)
        {
            cortar = texto.Length - 29;
            resumen = texto.Remove(29, cortar);
        }
        else
        { resumen = texto; }
 
        textoCompleto = resumen;
        valor = total.ToString("#,#.00");
 
        int nroEspacios = maxCar - (resumen.Length + valor.Length);
 
        for (int i = 0; i < nroEspacios; i++)
        {
            espacios += " ";
        }
        textoCompleto += espacios + valor;
        linea.AppendLine(textoCompleto);
    }
 
    public void AgregaArticulo(string articulo, int cant, decimal precio)
    {
        if (cant.ToString().Length <= 7 && precio.ToString().Length <= 11)
        {
            string elemento = "", espacios = "";
            bool bandera = false;
            int nroEspacios = 0;
 
            if (articulo.Length > 24)
            {
                nroEspacios = (7 - cant.ToString().Length);
                espacios = "";
                for (int i = 0; i < nroEspacios; i++)
                {
                    espacios += " ";
                }
                elemento += espacios + cant.ToString();
 
                nroEspacios = (11 - precio.ToString().Length);
                espacios = "";
                for (int i = 0; i < nroEspacios; i++)
                {
                    espacios += " ";
                }
                elemento += espacios + precio.ToString();//Agregamos el precio a la variable elemento
 
                int caracterActual = 0;
 
                for (int longitudTexto = articulo.Length; longitudTexto > 24; longitudTexto -= 24)
                {
                    if (bandera == false)
                    {
                        linea.AppendLine(articulo.Substring(caracterActual, 24) + elemento);
                        bandera = true;
                    }
                    else
                        linea.AppendLine(articulo.Substring(caracterActual, 24));
 
                    caracterActual += 24;
                }
                linea.AppendLine(articulo.Substring(caracterActual, articulo.Length - caracterActual));
 
            }
            else //Si no es mayor solo agregarlo, sin dar saltos de lineas
            {
                for (int i = 0; i < (24 - articulo.Length); i++)
                {
                    espacios += " "; //Agrega espacios para completar los 20 caracteres
                }
                elemento = articulo + espacios;
 
                nroEspacios = (7 - cant.ToString().Length);// +(20 - elemento.Length);
                espacios = "";
                for (int i = 0; i < nroEspacios; i++)
                {
                    espacios += " ";
                }
                elemento += espacios + cant.ToString();
 
                //Colocar el precio a la derecha.
                nroEspacios = (11 - precio.ToString().Length);
                espacios = "";
                for (int i = 0; i < nroEspacios; i++)
                {
                    espacios += " ";
                }
                elemento += espacios + precio.ToString();
 
                linea.AppendLine(elemento);//Agregamos todo el elemento: nombre del articulo, cant, precio, importe.
            }
        }
        else
        {
            linea.AppendLine("Los valores ingresados para esta fila");
            linea.AppendLine("superan las columnas soportdas por éste.");
            throw new Exception("Los valores ingresados para algunas filas del ticket\nsuperan las columnas soportdas por éste.");
        }
    }
    public void CortaTicket()
    {
        linea.AppendLine("\x1B" + "m"); //Caracteres de corte. Estos comando varian segun el tipo de impresora
        linea.AppendLine("\x1B" + "d" + "\x00"); //Avanza 9 renglones, Tambien varian
    }
 
    public void AbreCajon()
    {
        linea.AppendLine("\x1B" + "p" + "\x00" + "\x0F" + "\x96"); //Caracteres de apertura cajon 0
    }
 
    public void ImprimirTicket(string impresora)
    {
        RawPrinterHelper.SendStringToPrinter(impresora, linea.ToString()); //Imprime texto.
    }
}
 
public class RawPrinterHelper
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public class DOCINFOA
    {
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDocName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pOutputFile;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDataType;
    }
    [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
 
    [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool ClosePrinter(IntPtr hPrinter);
 
    [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
 
    [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndDocPrinter(IntPtr hPrinter);
 
    [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartPagePrinter(IntPtr hPrinter);
 
    [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndPagePrinter(IntPtr hPrinter);
 
    [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
 
    public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
    {
        Int32 dwError = 0, dwWritten = 0;
        IntPtr hPrinter = new IntPtr(0);
        DOCINFOA di = new DOCINFOA();
        bool bSuccess = false; // Assume failure unless you specifically succeed.
 
        di.pDocName = "Ticket de Venta";
        di.pDataType = "RAW";
 
 
        if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
        {
 
            if (StartDocPrinter(hPrinter, 1, di))
            {
 
                if (StartPagePrinter(hPrinter))
                {
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
 
        if (bSuccess == false)
        {
            dwError = Marshal.GetLastWin32Error();
        }
        return bSuccess;
    }
 
    public static bool SendStringToPrinter(string szPrinterName, string szString)
    {
        IntPtr pBytes;
        Int32 dwCount;
        // How many characters are in the string?
        dwCount = szString.Length;
        // Assume that the printer is expecting ANSI text, and then convert
        // 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;
    }
}
}

Código botón que imprime

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private void btnImprimir_Click(object sender, EventArgs e) { try { CrearTicket ticket = new CrearTicket();
 
        ticket.TextoIzquierda(" ");
        ticket.TextoCentro("TICKET CIERRE DE CAJA");
        ticket.TextoIzquierda(" ");
        ticket.TextoExtremos("FECHA : " + txtFecha.Text, "HORA : " + txtHora.Text);
        ticket.TextoIzquierda(" ");
        ticket.EncabezadoVenta();
        ticket.lineasGuio();
        foreach (DataGridViewRow fila in dataGridView1.Rows)
        {
            ticket.AgregaArticulo(fila.Cells[1].Value.ToString(), int.Parse(fila.Cells[0].Value.ToString()) , decimal.Parse(fila.Cells[3].Value.ToString()));
        }
        ticket.lineasIgual();
        ticket.AgregarTotales("          TOTAL COMPRADO : $ ", decimal.Parse(txtCompra.Text));
        ticket.AgregarTotales("          TOTAL VENDIDO  : $ ", decimal.Parse(txtVenta.Text));
        ticket.TextoIzquierda(" ");
        ticket.AgregarTotales("          GANANCIA       : $ ", decimal.Parse(txtResultado.Text));
        ticket.TextoIzquierda(" ");
        ticket.TextoIzquierda(" ");
        ticket.TextoIzquierda(" ");
        ticket.TextoIzquierda(" ");
        ticket.TextoIzquierda(" ");
        ticket.TextoIzquierda(" ");
        ticket.CortaTicket();
        ticket.ImprimirTicket("EPSON TM-T20II Receipt");
    }
    catch (Exception eeee) { }
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Wilfredo Patricio Castillo
Val: 707
Oro
Ha mantenido su posición en C sharp (en relación al último mes)
Gráfica de C sharp

Impresion de tickets C#

Publicado por Wilfredo Patricio Castillo (416 intervenciones) el 20/05/2017 00:25:18
Ese ejemplo tiene varios años en la web, pero si te fijas es justamente para imprimir en matricial, por eso que se usa la libreria RawPrinter, entonces para imprimir de manera gráfica y un código de barras, la cosa cambiaría ligeramente.

Saludos cordiales,
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Impresion de tickets C#

Publicado por Angel Rojas (1 intervención) el 20/05/2018 01:57:20
ya que le doy click al boton imprimir no me hace nada. eso con el nombre de mi impresora pero si lo cambio a "Microsoft XPS Document Writer" si me lo guarda correctamente y lo puedo visualizar en el bloc de notas alguna recomendacion para que lo pueda imprimir directamente a mi impresora ?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Wilfredo Patricio Castillo
Val: 707
Oro
Ha mantenido su posición en C sharp (en relación al último mes)
Gráfica de C sharp

Impresion de tickets C#

Publicado por Wilfredo Patricio Castillo (416 intervenciones) el 22/05/2018 00:50:36
Ponle el nombre de tu impresora, y que la misma esté establecida como predeterminada.

Ojo, que como ya te dije anteriormente, eso está enfocado a impresoras matriciales.

Saludos cordiales,
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Impresion de tickets C#

Publicado por Pedro (1 intervención) el 05/07/2018 04:34:54
Todo funciona bien ya logre imprimir desde mi aplicacion en c# solo tengo un problema al momento de imprimir a una impresora compartida desde otra pc le coloco el nombre de la impresora compartida pero no manda la impresion por la red....
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Andres Leonardo
Val: 2
Ha aumentado su posición en 39 puestos en C sharp (en relación al último mes)
Gráfica de C sharp

Impresion de tickets C#

Publicado por Andres Leonardo (1 intervención) el 01/02/2019 16:44:21
pon el nombre asi

1
"\\servidor\nombreimpresora"
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Impresion de tickets C#

Publicado por Cesar Rivera (2 intervenciones) el 17/06/2021 20:55:33
Compañero me podria indicar cuales serian los cambios que requeriria realizar, he intenado colocar imagen y colocar codigo de barras con la libreria barcode llib sin exito.
Salufdos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Impresion de tickets C#

Publicado por Cesar Rivera (2 intervenciones) el 02/07/2021 01:57:16
Buenos Dias Compañero, me podria orientar con ejemplo de como imprimir de manera grafica y la iompresion de codigo de barras, que instalado librerias , etc.. etc.. pero no he podido
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Impresion de tickets C#

Publicado por Andres (1 intervención) el 06/10/2019 17:45:03
Buenas tardes

como puedo dar formato "N2" en la siguiente linea:

ticket.AgregaArticulo(fila.Cells[1].Value.ToString(), int.Parse(fila.Cells[0].Value.ToString()) , decimal.Parse(fila.Cells[3].Value.ToString()));

necesito poner el ("N2") aqui: decimal.Parse(fila.Cells[3].Value.ToString()));

Pero no se como.

Gracias por la ayuda.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Impresion de tickets C#

Publicado por Hernan Serrano Morales (1 intervención) el 16/12/2021 18:22:40
Tal vez un poco tarde. Pero he modificado la clase para que imprima un logo. Necesita cambios para mejorarla. Pero por lo menos es un comienzo.
Espero que les sirva a los nuevos muchachos que estan iniciando en esta lides.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Receipt
{
public class CrearTicket
{
StringBuilder linea = new StringBuilder();
private Image headerImage = null;
//Creamos una variable para almacenar el numero maximo de caracteres que permitiremos en el ticket.
public int maxCar = 48, cortar;//Para una impresora ticketera que imprime a 40 columnas. La variable cortar cortara el texto cuando rebase el limte.

public Image HeaderImage
{
get { return headerImage; }
set { if (headerImage != value) headerImage = value; }
}

//Creamos el primer metodo, este dibujara lineas guion.
public string lineasGuio()
{
string lineasGuion = "";
for (int i = 0; i < maxCar; i++)
{
lineasGuion += "-";//Agregara un guio hasta llegar la numero maximo de caracteres.
}
return linea.AppendLine(lineasGuion).ToString(); //Devolvemos la lineaGuion
}

//Metodo para dibujar una linea con asteriscos
public string lineasAsteriscos()
{
string lineasAsterisco = "";
for (int i = 0; i < maxCar; i++)
{
lineasAsterisco += "*";//Agregara un asterisco hasta llegar la numero maximo de caracteres.
}
return linea.AppendLine(lineasAsterisco).ToString(); //Devolvemos la linea con asteriscos
}

//Realizamos el mismo procedimiento para dibujar una lineas con el signo igual
public string lineasIgual()
{
string lineasIgual = "";
for (int i = 0; i < maxCar; i++)
{
lineasIgual += "=";//Agregara un igual hasta llegar la numero maximo de caracteres.
}
return linea.AppendLine(lineasIgual).ToString(); //Devolvemos la lienas con iguales
}

//Creamos un metodo para poner el texto a la izquierda
public void TextoIzquierda(string texto)
{
//Si la longitud del texto es mayor al numero maximo de caracteres permitidos, realizar el siguiente procedimiento.
if (texto.Length > maxCar)
{
int caracterActual = 0;//Nos indicara en que caracter se quedo al bajar el texto a la siguiente linea
for (int longitudTexto = texto.Length; longitudTexto > maxCar; longitudTexto -= maxCar)
{
//Agregamos los fragmentos que salgan del texto
linea.AppendLine(texto.Substring(caracterActual, maxCar));
caracterActual += maxCar;
}
//agregamos el fragmento restante
linea.AppendLine(texto.Substring(caracterActual, texto.Length - caracterActual));
}
else
{
//Si no es mayor solo agregarlo.
linea.AppendLine(texto);
}
}

//Creamos un metodo para poner texto a la derecha.
public void TextoDerecha(string texto)
{
//Si la longitud del texto es mayor al numero maximo de caracteres permitidos, realizar el siguiente procedimiento.
if (texto.Length > maxCar)
{
int caracterActual = 0;//Nos indicara en que caracter se quedo al bajar el texto a la siguiente linea
for (int longitudTexto = texto.Length; longitudTexto > maxCar; longitudTexto -= maxCar)
{
//Agregamos los fragmentos que salgan del texto
linea.AppendLine(texto.Substring(caracterActual, maxCar));
caracterActual += maxCar;
}
//Variable para poner espacios restntes
string espacios = "";
//Obtenemos la longitud del texto restante.
for (int i = 0; i < (maxCar - texto.Substring(caracterActual, texto.Length - caracterActual).Length); i++)
{
espacios += " ";//Agrega espacios para alinear a la derecha
}

//agregamos el fragmento restante, agregamos antes del texto los espacios
linea.AppendLine(espacios + texto.Substring(caracterActual, texto.Length - caracterActual));
}
else
{
string espacios = "";
//Obtenemos la longitud del texto restante.
for (int i = 0; i < (maxCar - texto.Length); i++)
{
espacios += " ";//Agrega espacios para alinear a la derecha
}
//Si no es mayor solo agregarlo.
linea.AppendLine(espacios + texto);
}
}

//Metodo para centrar el texto
public void TextoCentro(string texto)
{
if (texto.Length > maxCar)
{
int caracterActual = 0;//Nos indicara en que caracter se quedo al bajar el texto a la siguiente linea
for (int longitudTexto = texto.Length; longitudTexto > maxCar; longitudTexto -= maxCar)
{
//Agregamos los fragmentos que salgan del texto
linea.AppendLine(texto.Substring(caracterActual, maxCar));
caracterActual += maxCar;
}
//Variable para poner espacios restntes
string espacios = "";
//sacamos la cantidad de espacios libres y el resultado lo dividimos entre dos
int centrar = (maxCar - texto.Substring(caracterActual, texto.Length - caracterActual).Length) / 2;
//Obtenemos la longitud del texto restante.
for (int i = 0; i < centrar; i++)
{
espacios += " ";//Agrega espacios para centrar
}

//agregamos el fragmento restante, agregamos antes del texto los espacios
linea.AppendLine(espacios + texto.Substring(caracterActual, texto.Length - caracterActual));
}
else
{
string espacios = "";
//sacamos la cantidad de espacios libres y el resultado lo dividimos entre dos
int centrar = (maxCar - texto.Length) / 2;
//Obtenemos la longitud del texto restante.
for (int i = 0; i < centrar; i++)
{
espacios += " ";//Agrega espacios para centrar
}

//agregamos el fragmento restante, agregamos antes del texto los espacios
linea.AppendLine(espacios + texto);

}
}

//Metodo para poner texto a los extremos
public void TextoExtremos(string textoIzquierdo, string textoDerecho)
{
//variables que utilizaremos
string textoIzq, textoDer, textoCompleto = "", espacios = "";

//Si el texto que va a la izquierda es mayor a 18, cortamos el texto.
if (textoIzquierdo.Length > 22)
{
cortar = textoIzquierdo.Length - 22;
textoIzq = textoIzquierdo.Remove(22, cortar);
}
else
{ textoIzq = textoIzquierdo; }

textoCompleto = textoIzq;//Agregamos el primer texto.

if (textoDerecho.Length > 24)//Si es mayor a 20 lo cortamos
{
cortar = textoDerecho.Length - 24;
textoDer = textoDerecho.Remove(24, cortar);
}
else
{ textoDer = textoDerecho; }

//Obtenemos el numero de espacios restantes para poner textoDerecho al final
int nroEspacios = maxCar - (textoIzq.Length + textoDer.Length);
for (int i = 0; i < nroEspacios; i++)
{
espacios += " ";//agrega los espacios para poner textoDerecho al final
}
textoCompleto += espacios + textoDerecho;//Agregamos el segundo texto con los espacios para alinearlo a la derecha.
linea.AppendLine(textoCompleto);//agregamos la linea al ticket, al objeto en si.
}

//Creamos el encabezado para los articulos
public void EncabezadoVenta()
{
//Escribimos los espacios para mostrar el articulo. En total tienen que ser 40 caracteres
linea.AppendLine("ITEM |CANT |PRECIO ");
}

public void Header(object sender, PrintPageEventArgs e)
{
//Image logo = Image.FromFile("D:\\Caribe1\\GlobaApp_WU\\GlobalAppDkt\\GlobalAppDkt\\Resources\\GlobalLogo_mini.png");
//e.Graphics.DrawImage(HeaderImage, 0, 0, 238, 73);
e.Graphics.DrawImage(HeaderImage, 40, 0, 177, 120);
}

public void PrintHeader(string impresora)
{
PrintDocument pd = new PrintDocument();
//PaperSize ps = new PaperSize("", 375, 550);

pd.PrintPage += new PrintPageEventHandler(Header);

pd.PrintController = new StandardPrintController();
pd.DefaultPageSettings.Margins.Left = 0;
pd.DefaultPageSettings.Margins.Right = 0;
pd.DefaultPageSettings.Margins.Top = 0;
pd.DefaultPageSettings.Margins.Bottom = 0;
pd.DefaultPageSettings.PaperSize = new PaperSize("", 375, 550);
pd.PrinterSettings.PrinterName = impresora;
pd.Print();

}

//Metodo para agregar los totales d ela venta
public void AgregarTotales(string texto, decimal total)
{
//Variables que usaremos
string resumen, valor, textoCompleto, espacios = "";

if (texto.Length > 29)//Si es mayor a 25 lo cortamos
{
cortar = texto.Length - 29;
resumen = texto.Remove(29, cortar);
}
else
{ resumen = texto; }

textoCompleto = resumen;
valor = total.ToString("#,#.00");//Agregamos el total previo formateo.

//Obtenemos el numero de espacios restantes para alinearlos a la derecha
int nroEspacios = maxCar - (resumen.Length + valor.Length);
//agregamos los espacios
for (int i = 0; i < nroEspacios; i++)
{
espacios += " ";
}
textoCompleto += espacios + valor;
linea.AppendLine(textoCompleto);
}

//Metodo para agreagar articulos al ticket de venta
public void AgregaArticulo(string articulo, int cant, decimal precio)
{
//Valida que cant precio e importe esten dentro del rango.
if (cant.ToString().Length <= 7 && precio.ToString().Length <= 11)
{
string elemento = "", espacios = "";
bool bandera = false;//Indicara si es la primera linea que se escribe cuando bajemos a la segunda si el nombre del articulo no entra en la primera linea
int nroEspacios = 0;

//Si el nombre o descripcion del articulo es mayor a 20, bajar a la siguiente linea
if (articulo.Length > 24)
{
//Colocar la cantidad a la derecha.
nroEspacios = (7 - cant.ToString().Length);
espacios = "";
for (int i = 0; i < nroEspacios; i++)
{
espacios += " ";//Generamos los espacios necesarios para alinear a la derecha
}
elemento += espacios + cant.ToString();//agregamos la cantidad con los espacios

//Colocar el precio a la derecha.
nroEspacios = (11 - precio.ToString().Length);
espacios = "";
for (int i = 0; i < nroEspacios; i++)
{
espacios += " ";//Genera los espacios
}
//el operador += indica que agregar mas cadenas a lo que ya existe.
elemento += espacios + precio.ToString();//Agregamos el precio a la variable elemento

int caracterActual = 0;//Indicara en que caracter se quedo al bajae a la siguiente linea

//Por cada 20 caracteres se agregara una linea siguiente
for (int longitudTexto = articulo.Length; longitudTexto > 24; longitudTexto -= 24)
{
if (bandera == false)//si es false o la primera linea en recorrerer, continuar...
{
//agregamos los primeros 20 caracteres del nombre del articulos, mas lo que ya tiene la variable elemento
linea.AppendLine(articulo.Substring(caracterActual, 24) + elemento);
bandera = true;//cambiamos su valor a verdadero
}
else
linea.AppendLine(articulo.Substring(caracterActual, 24));//Solo agrega el nombre del articulo

caracterActual += 24;//incrementa en 20 el valor de la variable caracterActual
}
//Agrega el resto del fragmento del nombre del articulo
linea.AppendLine(articulo.Substring(caracterActual, articulo.Length - caracterActual));

}
else //Si no es mayor solo agregarlo, sin dar saltos de lineas
{
for (int i = 0; i < (24 - articulo.Length); i++)
{
espacios += " "; //Agrega espacios para completar los 20 caracteres
}
elemento = articulo + espacios;

//Colocar la cantidad a la derecha.
nroEspacios = (7 - cant.ToString().Length);// +(20 - elemento.Length);
espacios = "";
for (int i = 0; i < nroEspacios; i++)
{
espacios += " ";
}
elemento += espacios + cant.ToString();

//Colocar el precio a la derecha.
nroEspacios = (11 - precio.ToString().Length);
espacios = "";
for (int i = 0; i < nroEspacios; i++)
{
espacios += " ";
}
elemento += espacios + precio.ToString();

linea.AppendLine(elemento);//Agregamos todo el elemento: nombre del articulo, cant, precio, importe.
}
}
else
{
linea.AppendLine("Los valores ingresados para esta fila");
linea.AppendLine("superan las columnas soportdas por éste.");
throw new Exception("Los valores ingresados para algunas filas del ticket\nsuperan las columnas soportdas por éste.");
}
}

//Metodos para enviar secuencias de escape a la impresora
//Para cortar el ticket
public void CortaTicket()
{
linea.AppendLine("\x1B" + "m"); //Caracteres de corte. Estos comando varian segun el tipo de impresora
linea.AppendLine("\x1B" + "d" + "\x00"); //Avanza 9 renglones, Tambien varian
}

//Para abrir el cajon
public void AbreCajon()
{
//Estos tambien varian, tienen que ever el manual de la impresora para poner los correctos.
linea.AppendLine("\x1B" + "p" + "\x00" + "\x0F" + "\x96"); //Caracteres de apertura cajon 0
//linea.AppendLine("\x1B" + "p" + "\x01" + "\x0F" + "\x96"); //Caracteres de apertura cajon 1
}

//Para mandara a imprimir el texto a la impresora que le indiquemos.
public void ImprimirTicket(string impresora)
{
//Este metodo recibe el nombre de la impresora a la cual se mandara a imprimir y el texto que se imprimira.
//Usaremos un código que nos proporciona Microsoft. https://support.microsoft.com/es-es/kb/322091
if (this.HeaderImage != null)
this.PrintHeader(impresora);

RawPrinterHelper.SendStringToPrinter(impresora, linea.ToString()); //Imprime texto.
//linea.Clear();//Al cabar de imprimir limpia la linea de todo el texto agregado.
}
}

//Clase para mandara a imprimir texto plano a la impresora
public class RawPrinterHelper
{
// Structure and API declarions:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)]
public string pDocName;
[MarshalAs(UnmanagedType.LPStr)]
public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)]
public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.

di.pDocName = "Ticket de Venta";//Este es el nombre con el que guarda el archivo en caso de no imprimir a la impresora fisica.
di.pDataType = "RAW";//de tipo texto plano
//di.pOutputFile = "D:\\ticket.txt";

// Open the printer.
if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
{
// Start a document.
if (StartDocPrinter(hPrinter, 1, di))
{
// Start a page.
if (StartPagePrinter(hPrinter))
{
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if (bSuccess == false)
{
dwError = Marshal.GetLastWin32Error();
}
return bSuccess;
}

public static bool SendStringToPrinter(string szPrinterName, string szString)
{
IntPtr pBytes;
Int32 dwCount;
// How many characters are in the string?
dwCount = szString.Length;
// Assume that the printer is expecting ANSI text, and then convert
// 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;
}

public static bool SendFileToPrinter(string szPrinterName, string szFileName)
{
// Open the file.
FileStream fs = new FileStream(szFileName, FileMode.Open);
// Create a BinaryReader on the file.
BinaryReader br = new BinaryReader(fs);
// Dim an array of bytes big enough to hold the file's contents.
Byte[] bytes = new Byte[fs.Length];
bool bSuccess = false;
// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);
int nLength;

nLength = Convert.ToInt32(fs.Length);
// Read the contents of the file into the array.
bytes = br.ReadBytes(nLength);
// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
fs.Close();
fs.Dispose();
fs = null;
return bSuccess;
}

}
}

Como se utiliza:

CrearTicket ticket = new CrearTicket();
ticket.maxCar = 40;
ticket.HeaderImage = Image.FromFile(@"D:\Caribe1\GlobaApp_WU\GlobalAppDkt\GlobalAppDkt\Resources\GlobalLogo_mini.png");
ticket.TextoIzquierda(" ");
ticket.TextoCentro("TICKET CIERRE DE CAJA");
ticket.TextoIzquierda(" ");
ticket.TextoExtremos("FECHA : " + DateTime.Now.Date, "HORA : " + DateTime.Now.Hour);
ticket.TextoIzquierda(" ");
ticket.EncabezadoVenta();
ticket.lineasGuio();
//foreach (DataGridViewRow fila in dataGridView1.Rows)
//{
// ticket.AgregaArticulo(fila.Cells[1].Value.ToString(), int.Parse(fila.Cells[0].Value.ToString()), decimal.Parse(fila.Cells[3].Value.ToString()));
//}
int contador = 1;
int seccion = 1;
for (int i = 1; i <= 50; i++)
{
ticket.AgregaArticulo("ITEM "+ contador.ToString(), i, 500);
contador++;
if (contador > 10)
{
contador = 1;
seccion++;
}
}
ticket.lineasIgual();
ticket.AgregarTotales(" TOTAL COMPRADO : $ ", decimal.Parse("1000000"));
ticket.AgregarTotales(" TOTAL VENDIDO : $ ", decimal.Parse("1000000"));
ticket.TextoIzquierda(" ");
ticket.AgregarTotales(" GANANCIA : $ ", decimal.Parse("1000000000"));
ticket.TextoIzquierda(" ");
ticket.TextoIzquierda(" ");
ticket.TextoIzquierda(" ");
ticket.TextoIzquierda(" ");
ticket.TextoIzquierda(" ");
ticket.TextoIzquierda(" ");
ticket.CortaTicket();
ticket.ImprimirTicket("LR2000");
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Impresion de tickets C#

Publicado por Juan Perez (1 intervención) el 26/04/2023 03:45:57
Para imprimir caracteres con acentos o con ñ.
De antenamo gracias.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar