| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169 |
- using Microsoft.AspNetCore.Mvc;
- using Spire.Pdf;
- using System.Drawing.Printing;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- namespace printservice.Controllers
- {
- public class PrintTextRequest
- {
- public required string PrinterIp { get; set; }
- public required string Text { get; set; }
- }
- [ApiController]
- [Route("api/printer")]
- public class PrinterController : ControllerBase
- {
- private readonly ILogger<PrinterController> _logger;
- public PrinterController(ILogger<PrinterController> logger)
- {
- _logger = logger;
- }
- [HttpGet("list")]
- public IActionResult GetPrinters()
- {
- try
- {
- // Obtener la lista de impresoras instaladas
- var printers = PrinterSettings.InstalledPrinters.Cast<string>().ToList();
- if (printers.Count == 0)
- {
- return NotFound("No se encontraron impresoras instaladas.");
- }
- return Ok(printers);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error al obtener la lista de impresoras.");
- return StatusCode(500, "Error interno del servidor al listar impresoras.");
- }
- }
- [HttpGet("get-local-ip")]
- public IActionResult GetLocalIP()
- {
- var hostName = Dns.GetHostName();// Nombre de la PC
- var localIP = Dns.GetHostAddresses(hostName)
- .Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)//Obtener solo IPv4
- .Select(ip => ip.ToString());
- return Ok(new
- {
- machineName = hostName,
- localIPs = localIP
- });
- }
- [HttpPost("open-drawer")]
- public IActionResult OpenDrawer([FromBody] string printerIp)
- {
- try
- {
- using (var client = new TcpClient(printerIp, 9100)) // Puerto común para impresoras ESC/POS
- using (var stream = client.GetStream())
- {
- // Comando para abrir la gaveta
- byte[] command = new byte[] { 0x1B, 0x70, 0x00, 0x19, 0xFA };
- stream.Write(command, 0, command.Length);
- }
- return Ok("Gaveta abierta correctamente.");
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error al abrir la gaveta: {Message}", ex.Message);
- return StatusCode(500, "Error interno del servidor al abrir la gaveta.");
- }
- }
- [HttpPost("print-text")]
- public IActionResult PrintText([FromBody] PrintTextRequest request)
- {
- try
- {
- using (var client = new TcpClient(request.PrinterIp, 9100)) // Puerto común para impresoras ESC/POS
- using (var stream = client.GetStream())
- {
- byte[] textBytes = Encoding.ASCII.GetBytes(request.Text + "\n");
- stream.Write(textBytes, 0, textBytes.Length);
- }
- return Ok("Texto enviado a imprimir correctamente.");
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error al imprimir texto.");
- return StatusCode(500, "Error interno del servidor al imprimir texto.");
- }
- }
- [HttpPost("print-ticket")]
- public IActionResult PrintTicket(IFormFile file, [FromForm] string printerName)
- {
- try
- {
- if (file == null || file.Length == 0)
- {
- return BadRequest("No se envió ningún archivo.");
- }
- if (string.IsNullOrEmpty(printerName))
- {
- return BadRequest("No se ingreso nombre de impresora");
- }
- // Guardar temporalmente el archivo
- var tempFilePath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.pdf ");
- using (var stream = new FileStream(tempFilePath, FileMode.Create))
- {
- file.CopyTo(stream);
- }
- // Cargar el PDF
- var pdfDocument = new PdfDocument();
- pdfDocument.LoadFromFile(tempFilePath);
- // Configurar la impresora
- pdfDocument.PrintSettings.PrinterName = printerName;
- pdfDocument.PrintSettings.SelectPageRange(1, pdfDocument.Pages.Count);
- pdfDocument.PrintSettings.SelectSinglePageLayout(Spire.Pdf.Print.PdfSinglePageScalingMode.FitSize);
- // Enviar a imprimir
- pdfDocument.Print();
- // Liberar recursos
- pdfDocument.Close();
- // Eliminar el archivo temporal
- System.IO.File.Delete(tempFilePath);
- return Ok("PDF enviado a imprimir correctamente.");
- }
- catch (Exception ex)
- {
- return StatusCode(500, $"Error al imprimir el PDF: {ex.Message}");
- }
- }
- [HttpPost("cut-paper")]
- public IActionResult CutPaper([FromBody] string printerIp)
- {
- try
- {
- using (var client = new TcpClient(printerIp, 9100)) // Puerto común para impresoras ESC/POS
- using (var stream = client.GetStream())
- {
- // Comando para cortar papel
- byte[] cutCommand = new byte[] { 0x1D, 0x69 }; // Comando ESC/POS para cortar papel
- stream.Write(cutCommand, 0, cutCommand.Length);
- }
- return Ok("Papel cortado correctamente.");
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error al cortar papel.");
- return StatusCode(500, "Error interno del servidor al cortar papel.");
- }
- }
- }
- }
|