How to print raw commands from Web REST APIs, WebServices, Remote URL files with Blazor
Product JSPrintManager for Blazor Published 07/08/2021 Updated 11/28/2024 Author Neodynamic
Overview
In this article, we'll cover how to send and print any Raw Printer Commands from different sources like a Web REST API or Web Service, a remote URL. Reading and sending the raw printer commands is done in Blazor code and our JSPrintManager fro Blazor solution that was specially designed for this kind of printing needs.
About Raw Printer Commands
First of all, let's clarify that "Raw Commands" refers to a stream of bytes that are expressed by following the syntax and rules of the Command Language (a.k.a. Programming Language) supported by the target printer. Some Printer Command Languages are composed of human-readable ASCII characters (like Zebra ZPL, EPL, etc) while others combine them with non-printable characters like is the case of EPSON ESC/POS, Postscript and HP-PCL languages.
On Windows, a PRN file also contains raw commands instructions for a printer which are usually created by a printer driver, therefor PRN files are printer model specific and will not work with other types of printers! It is not a simple text file you can open with a text editor software and print it as is, because it contains commands instructions in the form of bytes that must be sent to the printer without any modifications so the printer firmware can process them correctly.
Given said that, a plain text like "HELLO WORLD"
is NOT considered to be "raw commands" and you cannot expect to get the target printer to handle it and produce such output! Each printer brand supports one or more raw commands languages which are specified by the manufacturer. So, to expect some printing output, the correct "Raw Printer Commands" (which will depend in which of them the target printer supports) must be sent.
Now that you know what Raw Printer Commands refer to, in the following topics you'll learn how to read them from different sources and send them to the target printer by using Blazor and our JSPrintManager for Blazor solution.
Follow up these steps
- Be sure you install in your dev machine JSPrintManager (JSPM) (Available for Windows, Linux, Raspberry Pi & Mac)
This small app must be installed on each client that will print from your website! - In your Blazor project...
- Add a NuGet reference to the JSPrintManager Razor Component
- Add the JSPrintManager service...
- Add the following statement at the top of your
Startup
file
using Neodynamic.Blazor;
- For Blazor Server
Add the following line in theStartup's ConfigureServices
method
services.AddJSPrintManager();
For .NET 8+ you must use Interactive Server components and render mode, so add these settings:
builder.Services.AddRazorComponents() .AddInteractiveServerComponents();
app.MapRazorComponents<App>() .AddInteractiveServerRenderMode()
- For Blazor WebAssembly
Add the following line in theProgram's Main
method
builder.Services.AddJSPrintManager();
- For Blazor Server
- Add the following statement at the top of your
- Add the following statement in the
_Imports.razor
file
@using Neodynamic.Blazor
- Add the HttpClient service...
- For Blazor Server
Add the following line in theStartup's ConfigureServices
method
services.AddHttpClient();
- For Blazor WebAssembly
Add the following line in theProgram's Main
method
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)});
- For Blazor Server
- Add a new Razor Page and copy/paste the following code. Please read the following considerations depending on the sources from where the Raw Commands will be obtained and read the source code comments to understand the printing logic!
-
Printing Raw Printer Commands generated by a Web REST API or WebService
- If the raw printer commands are generated by a Web REST API or WebService (like the one offered by well knwon postal service companies), then copy/paste the following code and be sure you update the
'URL-TO-GET-RAW-PRINTER-COMMANDS'
value accord e.g.https://thirdparty.com/webapi
- IMPORTANT: The source from where the Raw Commands are returned must be configured to allow Cross-Origin Resource Sharing (CORS)
- If the raw printer commands are generated by a Web REST API or WebService (like the one offered by well knwon postal service companies), then copy/paste the following code and be sure you update the
-
Printing Raw Printer Commands from Remote URL files
- If the raw printer commands are stored in a file which could be hosted in an external website, then copy/paste the following code and be sure you update the
'URL-TO-GET-RAW-PRINTER-COMMANDS'
value to the correct URL i.e. to the external file e.g.https://somesite.com/file
- IMPORTANT: For Remote files, the server/website from where the Raw Commands are returned must be configured to allow Cross-Origin Resource Sharing (CORS)
- If the raw printer commands are stored in a file which could be hosted in an external website, then copy/paste the following code and be sure you update the
For .NET 8+ Blazor Server you must use Interactive Server render mode, so add these settings:
@page "/" @rendermode InteractiveServer @inject JSPrintManager JSPrintManager
@page "/" @inject JSPrintManager JSPrintManager <div> <strong>JSPM </strong><span>WebSocket Status </span> @if (JSPrintManager.Status == JSPMWSStatus.Open) { <span class="badge badge-success"> <i class="fa fa-check" /> Open </span> } else if (JSPrintManager.Status == JSPMWSStatus.Closed) { <span class="badge badge-danger"> <i class="fa fa-exclamation-circle" /> Closed! </span> <div> <strong>JSPrintManager (JSPM) App</strong> is not installed or not running! <a href="https://neodynamic.com/downloads/jspm" target="_blank">Download JSPM Client App...</a> </div> } else if (JSPrintManager.Status == JSPMWSStatus.Blocked) { <span class="badge badge-warning"> <i class="fa fa-times-circle" /> This Website is Blocked! </span> } else if (JSPrintManager.Status == JSPMWSStatus.WaitingForUserResponse) { <span class="badge badge-warning"> <i class="fa fa-user-circle" /> Waiting for user response... </span> } </div> @if (JSPrintManager.Status == JSPMWSStatus.Open) { @if (JSPrintManager.Printers == null) { <hr /> <div class="spinner-border text-info" role="status"> <span class="sr-only">Please wait...</span> </div> <strong><em>Getting local printers...</em></strong> } else { <div> <h1>Print Raw commands from Web REST API with Blazor</h1> <hr /> <EditForm Model="@MyPrinter"> <div class="form-check"> <InputCheckbox class="form-check-input" @bind-Value="UseDefaultPrinter" />Print to <strong>Default Printer?</strong><br /> </div> <p>or...</p> <p>Select an <strong>Installed Printer</strong>:</p> <InputSelect @bind-Value="MyPrinter.PrinterName" class="form-control form-control-sm"> @foreach (var p in JSPrintManager.Printers) { <option value="@p">@p</option> } </InputSelect> </EditForm> <br /><br /> <input type="button" value="Print Now..." @onclick="DoPrint" /> </div> } } @code { // An Installed Printer instance private InstalledPrinter MyPrinter { get; set; } = new(); // Use default printer? private bool UseDefaultPrinter = false; // Printing... async void DoPrint() { // Status = Open means that JSPM Client App is up and running! if (JSPrintManager.Status == JSPMWSStatus.Open) { // The HTTP Client using (var httpClient = new HttpClient()) { // Call Web REST API to get the raw printer commands using (var response = await httpClient.GetAsync("URL-TO-GET-RAW-PRINTER-COMMANDS")) { string cmds = await response.Content.ReadAsStringAsync(); // Create a ClientPrintJob var cpj = new ClientPrintJob(); // Set target Printer cpj.ClientPrinter = UseDefaultPrinter ? new DefaultPrinter() : MyPrinter; // Set the RAW commands to send to the printer... cpj.PrinterCommands = cmds; // PRINT IT!!! JSPrintManager.SendClientPrintJob(cpj); } } } } protected override void OnAfterRender(bool firstRender) { if (firstRender) { // Handle OnGetPrinters event... JSPrintManager.OnGetPrinters += () => { if (JSPrintManager.Printers != null && JSPrintManager.Printers.Length > 0) { // Display installed printers... StateHasChanged(); } else { Console.WriteLine("No printers found..."); } }; // Handle OnStatusChanged event to detect any WSS status change JSPrintManager.OnStatusChanged += () => { StateHasChanged(); // Status = Open means that JSPM Client App is up and running! if (JSPrintManager.Status == JSPMWSStatus.Open) { //Try getting local printers... JSPrintManager.TryGetPrinters(); } }; // Start WebSocket comm JSPrintManager.Start(); } base.OnAfterRender(firstRender); } }
-
- That's it! Run your website and test it. Click on Print Now... to print the Raw Commands without print dialog. You can print it to the Default client printer or you can get a list of the installed printers available at the client machine.
NOTE You can also print directly to any LPT Parallel Port, RS232 Serial Port or IP/Ethernet Printer although these scenarios have not been considered in this article for simplicity. For further details on those scenarios, please contact our tech support.