Convert Excel to PDF with Azure function in .NET standard application.
Syncfusion® Excel (XlsIO) library is a .NET Excel Library used to create, read, and edit Excel documents. Using this library, you can convert Excel documents into PDF in Azure functions.
Steps to convert Excel to PDF with Azure functions in a .NET Standard application programmatically:
Step 1: Create a new Azure function project.
Create a new Azure function project
Step 2: Select framework Azure Functions v2 (.NET Standard) and select HTTP trigger as follows.
Select framework and HTTP trigger
Step 3: Install the Syncfusion.XlsIORenderer.Net.Core NuGet package as a reference to your .NET Standard applications from NuGet.org.
Install NuGet package
Step 4: Include the following namespaces in the Function1.cs file.
C#
using System.IO; using Syncfusion.XlsIO; using Syncfusion.XlsIORenderer; using Syncfusion.Pdf; using System.Net.Http.Headers;
Step 5: Add the following code snippet to open and modify Excel document in Azure functions and return the output document to client end.
C#
[FunctionName("Function1")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
{
Stream stream = req.Content.ReadAsStreamAsync().Result;
// Instantiate the spreadsheet creation engine
using (ExcelEngine excelEngine = new ExcelEngine())
{
// Instantiate the Excel application object
IApplication application = excelEngine.Excel;// Assign default application version
application.DefaultVersion = ExcelVersion.Excel2013;IWorkbook workbook = application.Workbooks.Open(stream);
// Access a worksheet from the workbook
IWorksheet worksheet = workbook.Worksheets[0];// Open the Excel document to convert
XlsIORenderer renderer = new XlsIORenderer();// Initialize PDF document
PdfDocument pdfDocument = new PdfDocument();// Convert Excel document into PDF document
pdfDocument = renderer.ConvertToPDF(workbook);MemoryStream memoryStream = new MemoryStream();
// Save the PDF file
pdfDocument.Save(memoryStream);// Create the response to return
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);// Set the PDF document content response
response.Content = new ByteArrayContent(memoryStream.ToArray());// Set the content disposition as attachment
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Output.pdf"
};
// Set the content type as PDF format MIME type
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");// Return the response with output PDF stream
return response;
}
}
Step 6: Right-click the project and select Publish. Then, create a new profile in the Publish Window.
Publish window
Step 7: Create App service using Azure subscription and select a hosting plan.
Create App Service
Syncfusion® XlsIO library will work from basic hosting plan (B1). So, select the hosing plan as needed. Syncfusion XlsIO library will not work if the hosting plan is Consumption.
Configure Hosting Plan
Step 8: After creating the profile, click the Publish button.
Publish
Step 9: Now, go to the Azure portal and select the App Services. After running the service, click Get function URL by copying it. Then, paste it into the below client sample (which will request the Azure Function to convert Excel to PDF with Azure functions). You will get the PDF document as shown below.
Output PDF document
A complete Azure function sample can be downloaded from Convert ExcelToPDF from Azure Function.zip.
Steps to post the request to Azure function with template Excel document:
- Create a simple console application to request the Azure function API.
- Add the following code snippet into the Main method to request the Azure function with a template Excel document and get the converted PDF document.
C#
// Open the required template Excel file
Stream fileStream = File.Open("../../Data/Input.xlsx", FileMode.Open);// Create a memory stream to save the template
MemoryStream inputStream = new MemoryStream();// Copy the file stream into memory stream
fileStream.CopyTo(inputStream);// Dispose of the file stream
fileStream.Dispose();
try
{
// Create HttpWebRequest with hosted Azure function URL
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("Your Azure function URL");// Set request method as POST
req.Method = "POST";// Get the request stream to store the Excel document stream
Stream stream = req.GetRequestStream();// Write the Excel document stream into the request stream
stream.Write(inputStream.ToArray(), 0, inputStream.ToArray().Length);// Get the response from the Azure Function request
HttpWebResponse res = (HttpWebResponse)req.GetResponse();// Create file stream to save the output PDF file
FileStream outStream = File.Create("Sample.pdf");// Copy the response stream into the file stream
res.GetResponseStream().CopyTo(outStream);// Dispose of the input stream
inputStream.Dispose();// Dispose of the file stream
outStream.Dispose();
}
catch (Exception ex)
{
throw;
}// Launch the output document
System.Diagnostics.Process.Start("Sample.pdf");
The console application can be downloaded from DownloadConvertedPDF.zip.
Know more about the Essential® (XlsIO) library through the documentation, where you can find features like charts , drawing objects, chart to image conversion and worksheet to image conversion etc. with respective code examples.
Refer here to explore the rich set of Syncfusion® Excel (XlsIO) library features.
Note:
Starting with v16.2.0.x, if you reference Syncfusion® assemblies from a trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without a trial message.
Conclusion
I hope you enjoyed learning about how to convert Excel document to PDF with Azure function in .NET Standard.
You can refer to our ASP.NET Core XIsIO feature tour page to know about its other groundbreaking feature representations documentationand how to quickly get started for configuration specifications. You can also explore our ASP.NET Core XIsIO example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries 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!