PrinterController.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. using Microsoft.AspNetCore.Mvc;
  2. using Spire.Pdf;
  3. using System.Drawing.Printing;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. namespace printservice.Controllers
  8. {
  9. public class PrintTextRequest
  10. {
  11. public required string PrinterIp { get; set; }
  12. public required string Text { get; set; }
  13. }
  14. [ApiController]
  15. [Route("api/printer")]
  16. public class PrinterController : ControllerBase
  17. {
  18. private readonly ILogger<PrinterController> _logger;
  19. public PrinterController(ILogger<PrinterController> logger)
  20. {
  21. _logger = logger;
  22. }
  23. [HttpGet("list")]
  24. public IActionResult GetPrinters()
  25. {
  26. try
  27. {
  28. // Obtener la lista de impresoras instaladas
  29. var printers = PrinterSettings.InstalledPrinters.Cast<string>().ToList();
  30. if (printers.Count == 0)
  31. {
  32. return NotFound("No se encontraron impresoras instaladas.");
  33. }
  34. return Ok(printers);
  35. }
  36. catch (Exception ex)
  37. {
  38. _logger.LogError(ex, "Error al obtener la lista de impresoras.");
  39. return StatusCode(500, "Error interno del servidor al listar impresoras.");
  40. }
  41. }
  42. [HttpGet("get-local-ip")]
  43. public IActionResult GetLocalIP()
  44. {
  45. var hostName = Dns.GetHostName();// Nombre de la PC
  46. var localIP = Dns.GetHostAddresses(hostName)
  47. .Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)//Obtener solo IPv4
  48. .Select(ip => ip.ToString());
  49. return Ok(new
  50. {
  51. machineName = hostName,
  52. localIPs = localIP
  53. });
  54. }
  55. [HttpPost("open-drawer")]
  56. public IActionResult OpenDrawer([FromBody] string printerIp)
  57. {
  58. try
  59. {
  60. using (var client = new TcpClient(printerIp, 9100)) // Puerto común para impresoras ESC/POS
  61. using (var stream = client.GetStream())
  62. {
  63. // Comando para abrir la gaveta
  64. byte[] command = new byte[] { 0x1B, 0x70, 0x00, 0x19, 0xFA };
  65. stream.Write(command, 0, command.Length);
  66. }
  67. return Ok("Gaveta abierta correctamente.");
  68. }
  69. catch (Exception ex)
  70. {
  71. _logger.LogError(ex, "Error al abrir la gaveta: {Message}", ex.Message);
  72. return StatusCode(500, "Error interno del servidor al abrir la gaveta.");
  73. }
  74. }
  75. [HttpPost("print-text")]
  76. public IActionResult PrintText([FromBody] PrintTextRequest request)
  77. {
  78. try
  79. {
  80. using (var client = new TcpClient(request.PrinterIp, 9100)) // Puerto común para impresoras ESC/POS
  81. using (var stream = client.GetStream())
  82. {
  83. byte[] textBytes = Encoding.ASCII.GetBytes(request.Text + "\n");
  84. stream.Write(textBytes, 0, textBytes.Length);
  85. }
  86. return Ok("Texto enviado a imprimir correctamente.");
  87. }
  88. catch (Exception ex)
  89. {
  90. _logger.LogError(ex, "Error al imprimir texto.");
  91. return StatusCode(500, "Error interno del servidor al imprimir texto.");
  92. }
  93. }
  94. [HttpPost("print-ticket")]
  95. public IActionResult PrintTicket(IFormFile file, [FromForm] string printerName)
  96. {
  97. try
  98. {
  99. if (file == null || file.Length == 0)
  100. {
  101. return BadRequest("No se envió ningún archivo.");
  102. }
  103. if (string.IsNullOrEmpty(printerName))
  104. {
  105. return BadRequest("No se ingreso nombre de impresora");
  106. }
  107. // Guardar temporalmente el archivo
  108. var tempFilePath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.pdf ");
  109. using (var stream = new FileStream(tempFilePath, FileMode.Create))
  110. {
  111. file.CopyTo(stream);
  112. }
  113. // Cargar el PDF
  114. var pdfDocument = new PdfDocument();
  115. pdfDocument.LoadFromFile(tempFilePath);
  116. // Configurar la impresora
  117. pdfDocument.PrintSettings.PrinterName = printerName;
  118. pdfDocument.PrintSettings.SelectPageRange(1, pdfDocument.Pages.Count);
  119. pdfDocument.PrintSettings.SelectSinglePageLayout(Spire.Pdf.Print.PdfSinglePageScalingMode.FitSize);
  120. // Enviar a imprimir
  121. pdfDocument.Print();
  122. // Liberar recursos
  123. pdfDocument.Close();
  124. // Eliminar el archivo temporal
  125. System.IO.File.Delete(tempFilePath);
  126. return Ok("PDF enviado a imprimir correctamente.");
  127. }
  128. catch (Exception ex)
  129. {
  130. return StatusCode(500, $"Error al imprimir el PDF: {ex.Message}");
  131. }
  132. }
  133. [HttpPost("cut-paper")]
  134. public IActionResult CutPaper([FromBody] string printerIp)
  135. {
  136. try
  137. {
  138. using (var client = new TcpClient(printerIp, 9100)) // Puerto común para impresoras ESC/POS
  139. using (var stream = client.GetStream())
  140. {
  141. // Comando para cortar papel
  142. byte[] cutCommand = new byte[] { 0x1D, 0x69 }; // Comando ESC/POS para cortar papel
  143. stream.Write(cutCommand, 0, cutCommand.Length);
  144. }
  145. return Ok("Papel cortado correctamente.");
  146. }
  147. catch (Exception ex)
  148. {
  149. _logger.LogError(ex, "Error al cortar papel.");
  150. return StatusCode(500, "Error interno del servidor al cortar papel.");
  151. }
  152. }
  153. }
  154. }