We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to create a PDF file in Blazor using C#

Platform: ASP.NET Core - EJ 2 |
Control: PDF

Creating a PDF document from the scratch using Syncfusion .NET Core library is easy. This article explains how to create a PDF file in Blazor framework using C#.

Prerequisites

Creating a Blazor project

  • Enable Visual Studio to use preview SDKs:
  • Open Tools > Options in the menu bar.
  • Open the Projects and Solutions node. Open the .NET Core tab.
  • Check the box for Use previews of the .NET Core SDK. Select OK.
  • Restart the Visual Studio 2019.
  • Create a new project

Create a new Blazor project

  • Select Blazor App. Select Next.

Set project name and location

  • Select Blazor Server APP.

Select Project Type

Creating a PDF file in Blazor

Syncfusion PDF NuGet Reference

  • Add the following namespace in the Index.razor to create a PDF document from the scratch.
    @using Syncfusion.Pdf;
    @using Syncfusion.Pdf.Graphics;
    @using System.IO;
    @inject Microsoft.JSInterop.IJSRuntime JS
    
  • Add a button and hook the click event function.
    <button class="btn btn-primary" @onclick="@CreatePDF">Create PDF</button>
    
  • Add the following code to create a PDF file in Blazor. 
    @functions {
     
        void CreatePDF()
        {
            //Create a new PDF document
            PdfDocument document = new PdfDocument();
     
            //Add a page to the document
            PdfPage page = document.Pages.Add();
     
            //Create PDF graphics for the page
            PdfGraphics graphics = page.Graphics;
     
            //Set the standard font
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
     
            //Draw the text
            graphics.DrawString("Hello World!", font, PdfBrushes.Black, new Syncfusion.Drawing.PointF(0, 0));
     
            //Saving the PDF to the MemoryStream
            MemoryStream stream = new MemoryStream();
     
            document.Save(stream);
            document.Close(true);
     
     
            //Download the PDF in the browser.
        }
     
    }
    

To save the pdf document in the project folder:

  • Add the following code snippet in the created class file to save the pdf document in the project folder itself:
    System.IO.Stream output;
    output = System.IO.File.OpenWrite("output.pdf");​
     
    //Save the document.
    doc.Save(output);
     
    //Close the document.
    doc.Close(true);
    output.Close();​
    

 

To download the PDF file in browser

Create a class file with FileUtil name and add the following code to invoke the JavaScript action to download the file in the browser.

  • Add the following code in the created class file.
    public static class FileUtil
        {
            public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
                => js.InvokeAsync<object>(
                    "saveAsFile",
                    filename,
                    Convert.ToBase64String(data));
        }
    
  • Add the following JavaScript function in the _Host.cshtml in the pages folder.
    <script type="text/javascript">
            function saveAsFile(filename, bytesBase64) {
                if (navigator.msSaveBlob) {
                    //Download document in Edge browser
                    var data = window.atob(bytesBase64);
                    var bytes = new Uint8Array(data.length);
                    for (var i = 0; i < data.length; i++) {
                        bytes[i] = data.charCodeAt(i);
                    }
                    var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
                    navigator.msSaveBlob(blob, filename);
                }
                else {
                    var link = document.createElement('a');
                    link.download = filename;
                    link.href = "data:application/octet-stream;base64," + bytesBase64;
                    document.body.appendChild(link); // Needed for Firefox
                    link.click();
                    document.body.removeChild(link);
                }
            }
      </script>
    
  • Finally, add the following code in the Index.razor.
    //Download the PDF in the browser.
    JS.SaveAs("Sample.pdf", stream.ToArray());
    
  • The complete code of the PDF creation will look like below.
    @functions {
     
        void CreatePDF()
        {
            //Create a new PDF document
            PdfDocument document = new PdfDocument();
     
            //Add a page to the document
            PdfPage page = document.Pages.Add();
     
            //Create PDF graphics for the page
            PdfGraphics graphics = page.Graphics;
     
            //Set the standard font
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
     
            //Draw the text
            graphics.DrawString("Hello World!", font, PdfBrushes.Black, new Syncfusion.Drawing.PointF(0, 0));
     
            //Saving the PDF to the MemoryStream
            MemoryStream stream = new MemoryStream();
     
            document.Save(stream);
     
            document.Close(true);
     
            //Download the PDF in the browser.
            JS.SaveAs("Sample.pdf", stream.ToArray());
     
        }
     
    }
    

You can download the sample from BlazorPDFGettingStarted.zip

By executing the program, you will get the PDF file as follows.

Output PDF Document

Take a moment to peruse the documentation, where you can find other options like drawing right-to-left text and multi-column text, consuming TrueType fonts, Standard fonts, and CJK fonts. Also, the features like PDF form filling, convert HTML to PDF , and protect PDF documents with code examples.

Refer here to explore the rich set of Syncfusion Essential PDF features.

2X faster development

The ultimate ASP.NET Core UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment
Comments
Dave Vorgang
Jun 04, 2019

Do you have a product that will create a report in Blazor?

Reply
Surya Kumar [Syncfusion]
Jul 05, 2019

Hi Dave,

If you requirement with report to create and export only then you can use the Syncfusion.Report.Net.core for your requirement and the below documentation and knowledgebase article will helpful or you. https://help.syncfusion.com/aspnet-core/reportwriter/getting-started https://www.syncfusion.com/kb/10609/create-rdl-and-rdlc-reports-programmatically-with-asp-net-core

For a report component, we have already logged the feature for Blazor and track the status of the feature from below feedback, https://www.syncfusion.com/feedback/6689/report-viewer-for-blazor

Regards,

Surya Kumar

Ciaran Harper
Jul 04, 2019

I have Visual Studio 2019, but when I navigate to Tools > Options > Projects and Solutions > .NET Core I can only see a checkbox showing "Don't call MSBuild if a project appears to be up to date" and a drop down menu for "Logging Level" with the options "None", "Info" and "Verbose". I don't see a checkbox for "Use previews of the .NET Core SDK" anywhere.

Reply
Gowthamraj Kumar [Syncfusion]
Jul 04, 2019

Hi Ciaran,

We are using Visual Studio 2019 with a version of 16.0.0 in our environment. The preview option is available in Tools > Options > Projects and Solutions > .NET Core, "Use previews of the .NET Core SDK" checkbox is available in this version.

If you are using above 16.0.0 or latest version of Visual Studio, please check the below settings to enable the checkbox to use preview SDKs. Tools > Options > Environment > Preview Features > Use previews of the .NET Core SDK checkbox is available.

Please let us know if you need any further assistance on this.

Regards,

Gowthamraj K

Dino
Sep 24, 2019
<p></p><div class="pasteContent" style="display:inline;"><p>I am trying to create same behavior in latest Blazor server side release. But in FileUtil class</p> <pre><code>public static class FileUtil { public static Task SaveAs(this IJSRuntime js, string filename, byte[] data) { return js.InvokeAsync&lt;object&gt;( "saveAsFile", filename, Convert.ToBase64String(data)); } } </code></pre><p>I am getting Error CS0029 - Cannot implicitly convert type 'System.Threading.Tasks.ValueTask&lt;object&gt;' to 'System.Threading.Tasks.Task'<p></p> </object></p></div><br><p></p> Reply
Kalidass Kanagaraj [Syncfusion]
Sep 25, 2019
<p></p><div class="pasteContent" style="display:inline;"><p></p><div class="pasteContent" style="display:inline;"><p>Hi Dino</p> <p>The reported issue occurs in latest .NET Core update (since the KB article is older one). So we suggest you to use the following changes to get resolve this issue.</p> <ol> <li>Open the Index.razor and add the below highlighted line.</li> </ol> <pre><code>@using Syncfusion.Pdf; @using Syncfusion.Pdf.Graphics; @using System.IO; @inject Microsoft.JSInterop.IJSRuntime JS <button class="btn btn-primary" @onclick="@CreatePDF">Create PDF</button> </code></pre><ol> <li>Change the return type as ValueTask&lt;object&gt; instead of Task.</li> </ol> <pre><code>public static ValueTask&lt;object&gt; SaveAs(this IJSRuntime js, string filename, byte[] data) =&gt; js.InvokeAsync&lt;object&gt;( "saveAsFile", filename, Convert.ToBase64String(data)); </code></pre><p>Please try the above changes in your side and let us know if you have any concern.</p> <p>We have updated the modified sample for your reference <a rel='nofollow' href="https://www.syncfusion.com/downloads/support/directtrac/general/ze/BlazorPDFGettingStarted-1007429454">BlazorPDFGettingStarted.zip</a>. And also we have republished KB with updated details.</p> <p>Regards,</p> <p>Kalidass K</p> </div><br><p></p></div><p></p>
Adnan Ali
Feb 01, 2022

What if the content length exceeds one Page, Can content be added automatically on 2nd page

Reply

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile