0

I need to print a 2D QR code from a blazor server side app. I've used this post but PrintDialog is not working even after adding System.windows.Forms. Any idea on how to do it. My printer is GK420T connected to USB001.

user10191234
  • 531
  • 1
  • 4
  • 24

1 Answers1

0
  • First, add the following package to your Blazor server app project:
    Zebra.Sdk.Printer

  • Next, create a new C# class called LabelPrinter with the following code:

    using Zebra.Sdk.Comm;
    using Zebra.Sdk.Printer;
    using Zebra.Sdk.Printer.Discovery;
    
    public class LabelPrinter
    {
      private Connection printerConnection;
      private ZebraPrinter printer;
    
      public LabelPrinter(string ipAddress)
      {
        printerConnection = new TcpConnection(ipAddress, TcpConnection.DEFAULT_ZPL_TCP_PORT);
        printer = ZebraPrinterFactory.GetInstance(printerConnection);
      }
    
    public void PrintQRCode(string data, int x, int y, int size)
    {
      var qrCodeCommand = "^BQ,2,10^FDMA," + data + "^FS";
      var qrCodeSizeCommand = "^BY" + size.ToString();
      var qrCodePositionCommand = "^FO" + x.ToString() + "," + y.ToString();
    
      var labelCommands = new StringBuilder();
      labelCommands.AppendLine("^XA");
      labelCommands.AppendLine(qrCodePositionCommand);
      labelCommands.AppendLine(qrCodeCommand);
      labelCommands.AppendLine(qrCodeSizeCommand);
      labelCommands.AppendLine("^XZ");
    
      printerConnection.Open();
    
      if (printerConnection.Connected)
      {
          printerConnection.Write(labelCommands.ToString());
      }
    
      printerConnection.Close();
      }
     }
    

PrintQRCode method takes in the data to be encoded in the QR code, as well as the X and Y coordinates and size of the QR code.

The method creates the ZPL command for printing the QR code using the ^BQ command, and sets the data and size using the ^FD and ^BY parameters. It also sets the position of the QR code using the ^FO parameter.

Finally, the method constructs the full label commands using the StringBuilder class, and sends them to the printer over the network using the Write method.

Next, in your Blazor server app, create a new razor component called PrintLabel with the following code:

@page "/printlabel"
@inject NavigationManager NavigationManager

<h1>Print Label</h1>

<label for="label-content">Label Content:</label>
<textarea id="label-content" @bind="LabelContent"></textarea>

<button class="btn btn-primary" @onclick="PrintLabel">Print</button>

@code {
    private string LabelContent { get; set; }
    private async Task PrintLabel()
    {
        var printer = new LabelPrinter("192.168.0.100"); // Replace with your printer's IP address
        printer.PrintQRCode(LabelContent, 100, 100, 10);

        await NavigationManager.NavigateTo("/");
    }
}
Nb777
  • 1,658
  • 8
  • 27