Convert an Excel document to PDF in ASP.NET Core

16 May 20243 minutes to read

Syncfusion XlsIO is a .NET Core Excel library used to create, read, edit and convert Excel documents programmatically without Microsoft Excel or interop dependencies. Using this library, you can convert an Excel document to PDF in ASP.NET Core.

To quickly get started on converting an Excel document to a PDF in ASP.NET Core, please check out this video:

Steps to convert an Excel document to PDF in C#

Step 1: Create a new ASP.NET Core Web Application (Model-View-Controller).

Create a ASP.NET Core Web App project in visual studio

Step 2: Name the project.

Name the project

Step 3: Select the framework and click Create button.

Framework version

Step 4: Install the Syncfusion.XlsIORenderer.Net.Core NuGet package as a reference to your project from NuGet.org.

Install Syncfusion.XlsIORenderer.Net.Core NuGet Package

NOTE

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, you also have to add “Syncfusion.Licensing” assembly reference and include a license key in your projects. Please refer to this link to know about registering Syncfusion license key in your applications to use our components.

Step 5: Add a new button in the Index.cshtml as shown below.

@{Html.BeginForm("ConvertExceltoPDF", "Home", FormMethod.Get);
    {
        <div>
            <input type="submit" value="Convert Excel to PDF" style="width:150px;height:27px" />
        </div>
    }
    Html.EndForm();
}

Step 6: Include the following namespaces in HomeController.cs.

using Syncfusion.XlsIO;
using Syncfusion.XlsIORenderer;
using Syncfusion.Pdf;

Step 7: Include the below code snippet in HomeController.cs to convert an Excel document to PDF.

using (ExcelEngine excelEngine = new ExcelEngine())
{
  IApplication application = excelEngine.Excel;
  application.DefaultVersion = ExcelVersion.Xlsx;
  FileStream excelStream = new FileStream("Sample.xlsx", FileMode.Open, FileAccess.Read);
  IWorkbook workbook = application.Workbooks.Open(excelStream);

  //Initialize XlsIO renderer.
  XlsIORenderer renderer = new XlsIORenderer();

  //Convert Excel document into PDF document 
  PdfDocument pdfDocument = renderer.ConvertToPDF(workbook);

  //Create the MemoryStream to save the converted PDF.      
  MemoryStream pdfStream = new MemoryStream();

  //Save the converted PDF document to MemoryStream.
  pdfDocument.Save(pdfStream);
  pdfStream.Position = 0;

  //Download PDF document in the browser.
  return File(pdfStream, "application/pdf", "Sample.pdf");
}

A complete working example of how to convert an Excel document to PDF in ASP.NET Core is present on this GitHub page.

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

Output File

Click here to explore the rich set of Syncfusion Excel library (XlsIO) features.

An online sample link to convert an Excel document to PDF in ASP.NET Core.