Inquiridor
Imprimir porta COM1

Pergunta
-
Galera alguém sabe como imprimir uma string ou um txt diretamente na porta COM 1;
Fiz esse código mais não sei se esta correto:
//String para impressão private String listaItens() { PedidosDAO p = new PedidosDAO(); List<tbgItemPedido> pd = p.itemPedidoLista(Convert.ToInt32(dgvPedidos.CurrentRow.Cells[0].Value)); RestauranteDAO resDAO = new RestauranteDAO(); tbgRestaurante restaurante = resDAO.retornaRestauranteID(Restaurante); tbgCliente cliente = resDAO.retornaClienteID(Convert.ToInt32(dgvPedidos.CurrentRow.Cells[1].Value)); tbgEnderecoCliente enderecoCliente = resDAO.retornaEnderecoID(resDAO.retornaPedidoID(Convert.ToInt32(dgvPedidos.CurrentRow.Cells[0].Value)).idEnderecoCliente.Value); string teste = ""; teste += "====="+restaurante.nmRestaurante+"===== \r\n"; teste += "CLI.: " + cliente.nmCliente+"\r\n"; teste += "END.: " + enderecoCliente.dsLogradouro + "\r\n"; teste += "BAIRRO.: " + resDAO.retornaBairroID(enderecoCliente.idBairro.Value).nmBairro+"\r\n"; teste += "TEL.: " + cliente.cdContato1 + " | " + cliente.cdContato2+"\r\n"; teste += "Nº.: " + enderecoCliente.nnLogradouro+ "\r\n\r\n"; teste += "PEDIDO Nº.: " + dgvPedidos.CurrentRow.Cells[0].Value.ToString() + "\r\n"; teste += "====== ITENS DO PEDIDO ======="+"\r\n\r\n"; decimal total = 0; decimal desconto = 0; decimal frete = 0; foreach(var i in pd) { teste += i.qtd.ToString() + "x"; teste += "("+p.lidaCategoriaPedido(i.idItem.Value)+")"+"\r\n"; teste += i.tbgItem.nmItem +" "; teste += string.Format("{0:C}" , i.vlItem.Value); teste += "\r\n"; teste += "----ACRÉSCIMOS---\r\n"; foreach(var c in p.subItemPedidoID(i.idItemPedido)) { teste += c.nmSubItem +" - " + String.Format("{0:C}",c.Valor) + "\r\n"; total += c.Valor; } total += i.vlItem.Value; desconto += i.vlDesconto.Value; teste += "Obs.:" + i.dsObservacao+"\r\n"; teste += "----------------------- \r\n"; } teste += "\r\n"; teste += "DESCONTO.: " + String.Format("{0:C}", desconto) + "\r\n\r\n"; teste += "FRETE.: " + String.Format("{0:C}",resDAO.retornaFrete(Restaurante, enderecoCliente.idBairro.Value))+"\r\n\r\n"; if(resDAO.retornaFrete(Restaurante, enderecoCliente.idBairro.Value) > 0) { frete = resDAO.retornaFrete(Restaurante, enderecoCliente.idBairro.Value); } teste += "EMISSÃO.: "+DateTime.Now.ToString()+"\r\n\r\n"; teste += "TOTAL Á PAGAR: " + String.Format("{0:C}", total+frete)+"\r\n"; return teste; }
Código para impressão na COM1:
System.IO.Ports.SerialPort s = new System.IO.Ports.SerialPort("COM1", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); s.Open(); s.Write(listaItens()); s.Close();
Todas as Respostas
-
Olá Raniel eu utilizo exatamente este código para imprimir na COM1, a única coisa que tem que ver é os caracteres de controle da impressora, exemplo se for uma zebra ao inves de imprimir somente texto direto pode-se fazer necessário usar a linguagem ZPL.
-
Olá Raniel eu utilizo exatamente este código para imprimir na COM1, a única coisa que tem que ver é os caracteres de controle da impressora, exemplo se for uma zebra ao inves de imprimir somente texto direto pode-se fazer necessário usar a linguagem ZPL.
Ah entendo, vou verificar a configuração das impressoras que vou utilizar, vlw obrigado. -
Olá Raniel eu utilizo exatamente este código para imprimir na COM1, a única coisa que tem que ver é os caracteres de controle da impressora, exemplo se for uma zebra ao inves de imprimir somente texto direto pode-se fazer necessário usar a linguagem ZPL.
Ah entendo, vou verificar a configuração das impressoras que vou utilizar, vlw obrigado.
Olha como ficou o cupom, na bemactech saiu assim mais em uma epson funcionou direitinho:
está impressora é USB no caso eu imprimo tanto Serial como USB.
-
Raniel, pode estar relacionado também com os caracteres de controle da impressora, estou mandando em anexo um modelo que uso para poder realizar o envio dos dados para os diversos tipos de porta de impressão inclusive USB, mas creio que seu fonte está correto é mais questão dos caracteres de controle de impressão do próprio device, a Bematech pode até tentar monitorar fazer uma impressão pelos softwares deles e monitorar com o hyper terminal a porta e verificar a escrita:
using System; using System.Collections.Generic; using System.IO; using System.IO.Ports; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Core { public class Impressora { [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 void EnviarDadosPortaSerial(string conteudo, string nomePorta) { SerialPort serialPort = new SerialPort(nomePorta, 9600, Parity.None, 8, StopBits.One); serialPort.Close(); serialPort.Open(); serialPort.Encoding = Encoding.GetEncoding(850); serialPort.Write(conteudo); serialPort.Close(); } public void EnviarDadosPortaParalela(string conteudo, string nomePorta) { string caminho = System.Windows.Forms.Application.StartupPath; StreamWriter etiqueta = new StreamWriter(Path.Combine(caminho, "Etiqueta.txt"), false, Encoding.GetEncoding(850)); etiqueta.Write(conteudo); etiqueta.Close(); System.IO.File.Copy(Path.Combine(caminho, "Etiqueta.txt"), nomePorta); System.IO.File.Delete(Path.Combine(caminho, "Etiqueta.txt")); etiqueta.Dispose(); } public void EnviarDadosPortaUSB(string conteudo, string nomeImpressora) { IntPtr pBytes; Int32 dwCount; dwCount = (conteudo.Length + 1) * Marshal.SystemMaxDBCSCharSize; Encoding encoding = Encoding.GetEncoding(850); byte[] strBytes = encoding.GetBytes(conteudo); conteudo = encoding.GetString(strBytes); pBytes = Marshal.StringToCoTaskMemAnsi(conteudo); //Permite a utilização de Unicode, sem este código não sai os acentos Marshal.Copy(strBytes, 0, pBytes, strBytes.Length); //Envia dados para impressora SendBytesToPrinter(nomeImpressora, pBytes, dwCount); Marshal.FreeCoTaskMem(pBytes); } 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 = "Etiqueta Manual"; di.pDataType = "RAW"; // 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; } } }
-
Raniel, pode estar relacionado também com os caracteres de controle da impressora, estou mandando em anexo um modelo que uso para poder realizar o envio dos dados para os diversos tipos de porta de impressão inclusive USB, mas creio que seu fonte está correto é mais questão dos caracteres de controle de impressão do próprio device, a Bematech pode até tentar monitorar fazer uma impressão pelos softwares deles e monitorar com o hyper terminal a porta e verificar a escrita:
using System; using System.Collections.Generic; using System.IO; using System.IO.Ports; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Core { public class Impressora { [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 void EnviarDadosPortaSerial(string conteudo, string nomePorta) { SerialPort serialPort = new SerialPort(nomePorta, 9600, Parity.None, 8, StopBits.One); serialPort.Close(); serialPort.Open(); serialPort.Encoding = Encoding.GetEncoding(850); serialPort.Write(conteudo); serialPort.Close(); } public void EnviarDadosPortaParalela(string conteudo, string nomePorta) { string caminho = System.Windows.Forms.Application.StartupPath; StreamWriter etiqueta = new StreamWriter(Path.Combine(caminho, "Etiqueta.txt"), false, Encoding.GetEncoding(850)); etiqueta.Write(conteudo); etiqueta.Close(); System.IO.File.Copy(Path.Combine(caminho, "Etiqueta.txt"), nomePorta); System.IO.File.Delete(Path.Combine(caminho, "Etiqueta.txt")); etiqueta.Dispose(); } public void EnviarDadosPortaUSB(string conteudo, string nomeImpressora) { IntPtr pBytes; Int32 dwCount; dwCount = (conteudo.Length + 1) * Marshal.SystemMaxDBCSCharSize; Encoding encoding = Encoding.GetEncoding(850); byte[] strBytes = encoding.GetBytes(conteudo); conteudo = encoding.GetString(strBytes); pBytes = Marshal.StringToCoTaskMemAnsi(conteudo); //Permite a utilização de Unicode, sem este código não sai os acentos Marshal.Copy(strBytes, 0, pBytes, strBytes.Length); //Envia dados para impressora SendBytesToPrinter(nomeImpressora, pBytes, dwCount); Marshal.FreeCoTaskMem(pBytes); } 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 = "Etiqueta Manual"; di.pDataType = "RAW"; // 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; } } }
Vou testar novamente