How to implement silent print in Blazor PDF viewer?
Description:
This article explains how to implement silent printing of PDF documents using a Windows Service in Blazor PDF Viewer. The sample demonstrates how to print PDFs silently (without user intervention) by leveraging the Syncfusion PDF Viewer control in a Windows Service environment. You can integrate this service with your Blazor application to trigger silent print jobs seamlessly.
Solution:
To perform silent printing, create a Windows Service that uses Syncfusion’s PdfViewerControl to load and print PDF documents directly to a specified printer. The service listens for print requests and processes them silently in the background without displaying any UI or requiring user interaction.
Prerequisites:
- Syncfusion PDF Viewer Control: The PdfViewerControl must be available and referenced in your service project.
- Basic Knowledge of Windows Services and Command Prompt: Familiarity with building and managing Windows Services and running commands in an elevated Command Prompt.
- Syncfusion Blazor PDF Viewer Setup: Ensure you have installed and set up the Syncfusion Blazor PDF Viewer component in your Blazor project. If you haven’t already done so, you can follow the Syncfusion Blazor PDF Viewer - Getting Started guide.
- Basic Knowledge of Blazor: Familiarity with Blazor components, how to bind events, and handle component references will be helpful in implementing this solution.
Code Snippet:
Use the following code snippet inside your Windows Service project to implement the silent printing method.
public IHttpActionResult Print()
{
try
{
string document = string.Empty;
var stream = Request.Content.ReadAsStreamAsync().Result;
PdfViewerControl pdfViewerControl = new PdfViewerControl();
// Load the PDF document to be printed.
pdfViewerControl.Load(stream);
string printerName = "Pass your printer name here…";
// Print the PDF document silently using the printer name.
pdfViewerControl.Print(printerName);
return Ok("Print completed");
}
catch (Exception ex)
{
return Ok(ex.Message);
}
}
Use the following Code Snippet to implement silent print in Blazor PDF viewer
Home.razor
@page "/"
@* @using PdfiumViewer *@
@using Syncfusion.Pdf.Parsing;
@using Syncfusion.Blazor.SfPdfViewer
@using Syncfusion.Blazor.Buttons
@inject IJSRuntime JsRuntime;
@using System.Drawing
@using System.Drawing.Printing
@using System.Net.Http
@inject HttpClient Http
<SfButton @onclick="Print">Print</SfButton>
<SfPdfViewer2 @ref="PDFViewer" Height="100%" Width="100%" DocumentPath="@DocumentPath">
<PdfViewerEvents DownloadEnd="DownloadEnd">
</PdfViewerEvents>
</SfPdfViewer2>
@code {
public string docBase64 = "";
public string DocumentPath => @"wwwroot\Data\pdf-Succinctly.pdf";
public SfPdfViewer2 PDFViewer { get; set; }
public async void DownloadEnd(DownloadEndEventArgs args)
{
string base64String = args.DownloadDocument;
byte[] bytes = Convert.FromBase64String(base64String.Split(",")[1]);
StreamContent streamContent = new StreamContent(new MemoryStream(bytes));
HttpResponseMessage httpResponseMessage = await Http.PostAsync("/api/print", streamContent);
string message = await httpResponseMessage.Content.ReadAsStringAsync();
}
public async void Print(MouseEventArgs args)
{
await PDFViewer.DownloadAsync();
}
}
Program.cs
using BlazorSilentPrintSample.Components;
using Syncfusion.Blazor;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddSignalR(o => { o.MaximumReceiveMessageSize = 102400000; });
builder.Services.AddMemoryCache();
builder.Services.AddSyncfusionBlazor();
builder.Services.AddScoped(sp =>
new HttpClient
{
BaseAddress = new Uri("http://localhost:9000/")
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();
Key Features Used in the Code:
- PdfViewerControl: Syncfusion’s control used to load and manipulate PDF documents programmatically.
- Load(stream): Method to load the PDF document from a stream into the PdfViewerControl.
- Print(printerName): Method to silently print the loaded PDF document to the specified printer without user interaction.
Sample:
You can download the sample in the provided Link.
Steps to run the sample:
Step 1: Right-click on your Windows Service project or solution in Visual Studio and select Rebuild to build the latest version.
Step 2: Open Command Prompt as Administrator:
- Click Start and search for Command Prompt.
- Right-click it and select Run as administrator.
Step 3: In the Command Prompt, navigate to the .NET Framework directory by executing:
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
Step 4: Now Go to your project source folder > bin > Debug and copy the full path of your Windows Service exe file.
Step 5: Open the command prompt and fire the below command and press ENTER for Installing a Windows Service.
Syntax:
InstallUtil.exe + Your copied path + \your service name + .exe
Our path:
installUtil.exe C:\Users\user1\Downloads\WindowsService-937552292\WindowsService\bin\Debug\WindowsService.exe
Step 6: Check the status of a Windows Service by following the below steps:
- Press Window key + R.
- Type services.msc
- Find your Service.
Step 7: Run the blazor application and do the modifications
Step 8: Click the print button to perform silent printing in blazor.
Conclusion:
We hope this article has guided you on How to implement silent print in Blazor PDF viewer.
You can refer to Blazor Pdf Viewer feature tour page to learn about its other groundbreaking features, documentation, and how to quickly get started for configuration specifications. You can also explore our Blazor PDF Viewer example to understand how to create and manipulate data.
For current customers, our Blazor components are available on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to evaluate our Blazor PDF Viewer and other Blazor components.
If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!