Convert Excel XLSX to PDF

The Excel to PDF Converter component allows you to convert XLSX Excel documents to PDF.

This component is bundled and distributed as two separate NuGet packages for Windows and Linux, each including the same .NET Standard 2.0 library and different native runtimes. Targeting .NET Standard 2.0 makes the packages compatible with a wide range of .NET Core and .NET Framework versions.

You can reference the HiQPdf.Next.ExcelToPdf.Windows NuGet package in applications running on Windows or the HiQPdf.Next.ExcelToPdf.Linux NuGet package in applications running on Linux to enable Excel to PDF conversion in your application. The package for Windows is referenced by the HiQPdf.Next.Windows metapackage for all components, and the package for Linux is referenced by the HiQPdf.Next.Linux metapackage for all components.

There are also multiplatform metapackages that reference both the Windows and Linux Excel to PDF packages: HiQPdf.Next.ExcelToPdf for the Excel to PDF functionality and HiQPdf.Next for the entire HiQPdf Next library.

Overview

The HiQPdf.NextExcelToPdfConverter class allows you to load an XLSX file and generate a PDF document, with optional control over page formatting, layout and visual elements such as headers and footers.

The converter has options to keep the column widths and row heights from the Excel document, to insert a PDF page break between content coming from multiple worksheets in the same workbook, to display or hide the worksheet title in PDF.

Create the Excel to PDF Converter

The HiQPdf.NextExcelToPdfConverter class is used to convert XLSX documents to PDF. You can create an instance using the default constructor, which initializes the converter with standard settings. These settings can later be customized through the ExcelToPdfConverterPdfDocumentOptions property which exposes an object of ExcelToPdfDocumentOptions type controlling various aspects of the generated PDF document and through properties like ExcelToPdfConverterKeepColumnWidths and ExcelToPdfConverterKeepRowHeights which control the PDF generation process.

Create a Excel to PDF Converter Instance
// Create a new Excel to PDF converter instance
ExcelToPdfConverter excelToPdfConverter = new ExcelToPdfConverter();

Note that ExcelToPdfConverter instances are not reusable. You must create a new instance for each conversion. Reusing an instance after a completed conversion will result in an exception.

Configure the PDF Page Settings

The format of the generated PDF document pages is controlled primarily by the ExcelToPdfDocumentOptionsUsePageSettingsFromExcel property, which specifies whether to use the page settings from the Excel document or custom values defined in code. An object of type ExcelToPdfDocumentOptions is exposed through the ExcelToPdfConverterPdfDocumentOptions property.

If UsePageSettingsFromExcel is set to true, the converter will use the page size, orientation and margins defined in the Excel document. In this case, you can also choose whether to use the page settings from the first worksheet or from the active worksheet through the ExcelToPdfDocumentOptionsUseFirstWorksheetPageSettings property. The following example shows how to enable this behavior.

Use Page Settings from Excel
excelToPdfConverter.PdfDocumentOptions.UsePageSettingsFromExcel = true;
excelToPdfConverter.PdfDocumentOptions.UseFirstWorksheetPageSettings = true;

If UsePageSettingsFromExcel is set to false, the converter will use the custom PDF page settings defined through the ExcelToPdfConverterPdfDocumentOptions property. The following example shows how to configure custom page size, orientation and margins.

Use Custom PDF Page Settings
excelToPdfConverter.PdfDocumentOptions.UsePageSettingsFromExcel = false;
excelToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
excelToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Landscape;
excelToPdfConverter.PdfDocumentOptions.LeftMargin = 20;
excelToPdfConverter.PdfDocumentOptions.RightMargin = 20;
excelToPdfConverter.PdfDocumentOptions.TopMargin = 30;
excelToPdfConverter.PdfDocumentOptions.BottomMargin = 30;

Keep Column Widths from Excel

The ExcelToPdfConverterKeepColumnWidths property controls whether to keep the original Excel column widths percentages in the generated PDF document. The default value is true which means that the converter will try to preserve the percentage of each column width from the total width in the generated PDF.

Keep Column Widths from Excel Document
excelToPdfConverter.KeepColumnWidths = true;

Keep Row Heights from Excel

The ExcelToPdfConverterKeepRowHeights property controls whether to keep the original Excel row heights in the generated PDF document. The default value is true which means that the converter will try to preserve the height of each row in the generated PDF.

Keep Row Heights from Excel Document
excelToPdfConverter.KeepRowHeights = true;

Convert Only the First Worksheet or All Worksheets

The ExcelToPdfDocumentOptionsConvertOnlyFirstWorksheet property controls whether the converter will convert only the first worksheet or all worksheets in the workbook. The default value is false which means that the converter will convert all worksheets in the workbook.

The ExcelToPdfDocumentOptions object is exposed through the ExcelToPdfConverterPdfDocumentOptions property.

If all worksheets in the workbook are converted, you can choose whether each worksheet starts on a new PDF page using the ExcelToPdfDocumentOptionsPageBreakBetweenWorksheets property. By default this property is set to true and each worksheet starts on a new PDF page.

The following example shows how to enable the conversion of all worksheets in the workbook and to start each worksheet on a new PDF page.

Convert All Worksheets
excelToPdfConverter.PdfDocumentOptions.ConvertOnlyFirstWorksheet = false;
excelToPdfConverter.PdfDocumentOptions.PageBreakBetweenWorksheets = true;

Display or Hide the Worksheet Title

The ExcelToPdfDocumentOptionsDisplayWorksheetTitle property controls whether the worksheet title is displayed at the top of the worksheet content in the PDF document. The default value is true which means that the converter will display the worksheet title.

The ExcelToPdfDocumentOptions object is exposed through the ExcelToPdfConverterPdfDocumentOptions property.

The following example shows how to display the worksheet title before the worksheet content in the PDF document.

Display Worksheet Title
excelToPdfConverter.PdfDocumentOptions.DisplayWorksheetTitle = true;

Add HTML Headers and Footers

You can add a header or footer from a URL or from an HTML string. The header and footer can include variables such as {page_number} or {total_pages} and support automatic resizing.

The creation of the HTML header and footer is controlled by the ExcelToPdfDocumentOptionsPdfHtmlHeader and ExcelToPdfDocumentOptionsPdfHtmlFooter properties. These properties expose objects of type PdfHtmlHeaderFooter, which derives from PdfHtmlTemplate.

The ExcelToPdfDocumentOptions object is exposed through the ExcelToPdfConverterPdfDocumentOptions property.

The header and footer options are similar to those available in the HTML to PDF Converter and are described in detail in the HTML Header and Footer with Page Numbers documentation section.

Convert Excel to PDF

To convert an Excel document from a memory buffer to a PDF document in a memory buffer use the ExcelToPdfConverterConvertToPdf(Byte) method. The parameter is the Excel document read into a memory buffer.

Convert Excel from Memory to PDF in Memory
byte[] outPdfBuffer = excelToPdfConverter.ConvertToPdf(excelBytes);

To convert an Excel file to a PDF document in a memory buffer use the ExcelToPdfConverterConvertToPdf(String) method. The parameter is the full path of the Excel file to be converted.

Convert Excel File to PDF in Memory
byte[] outPdfBuffer = excelToPdfConverter.ConvertToPdf(excelFilePath);

After conversion the resulting PDF document is returned as a byte array for in-memory processing such as streaming to a web client or saving to a database or a file.

For example you can write the byte array to disk to store the PDF as a file.

Write PDF Data to File
File.WriteAllBytes("output.pdf", outPdfBuffer);

There are also methods to convert an Excel document to a PDF file directly.

To convert an Excel document from a memory buffer to a PDF file use the ExcelToPdfConverterConvertToPdfFile(Byte, String) method. The first parameter is the Excel document read into a memory buffer and the second parameter is the full path of the output PDF file.

Convert Excel from Memory to PDF File
excelToPdfConverter.ConvertToPdfFile(excelBytes, outputPdfFilePath);

To convert an Excel file to a PDF file use the ExcelToPdfConverterConvertToPdfFile(String, String) method. The first parameter is the full path of the Excel file to be converted and the second parameter is the full path of the output PDF file.

Convert Excel File to PDF File
excelToPdfConverter.ConvertToPdfFile(excelFilePath, outputPdfFilePath);

Asynchronous Excel to PDF Methods

There are also asynchronous variants of these methods that follow the Task-based Asynchronous Pattern (TAP) in .NET, allowing Excel to PDF conversion to run in parallel using async and await. These methods share the same names as their synchronous counterparts and include the "Async" suffix. They also accept an optional System.ThreadingCancellationToken parameter that can be used to cancel the conversion operation where applicable.

To convert an Excel document from a memory buffer to a PDF document in a memory buffer, use the ExcelToPdfConverterConvertToPdfAsync(Byte, CancellationToken) method. The parameter is the Excel document read into a memory buffer.

Asynchronously Convert Excel from Memory to PDF in Memory
byte[] outPdfBuffer = await excelToPdfConverter.ConvertToPdfAsync(excelBytes);

To convert an Excel file to a PDF document in a memory buffer, use the ExcelToPdfConverterConvertToPdfAsync(String, CancellationToken) method. The parameter is the full path of the Excel file to be converted.

Asynchronously Convert Excel File to PDF in Memory
byte[] outPdfBuffer = await excelToPdfConverter.ConvertToPdfAsync(excelFilePath);

After conversion, the resulting PDF document is returned as a byte array for in-memory processing such as streaming to a web client or saving to a database or a file.

There are also methods to convert an Excel document to a PDF file directly.

To convert an Excel document from a memory buffer to a PDF file, use the ExcelToPdfConverterConvertToPdfFileAsync(Byte, String, CancellationToken) method. The first parameter is the Excel document read into a memory buffer and the second parameter is the full path of the output PDF file.

Asynchronously Convert Excel from Memory to PDF File
await excelToPdfConverter.ConvertToPdfFileAsync(excelBytes, outputPdfFilePath);

To convert an Excel file to a PDF file, use the ExcelToPdfConverterConvertToPdfFileAsync(String, String, CancellationToken) method. The first parameter is the full path of the Excel file to be converted and the second parameter is the full path of the output PDF file.

Asynchronously Convert Excel File to PDF File
await excelToPdfConverter.ConvertToPdfFileAsync(excelFilePath, outputPdfFilePath);

Code Sample - Convert Excel to PDF

Convert Excel to PDF in ASP.NET Core
using System;
using System.IO;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using HiQPdf_Next_AspNetDemo.Models;

using HiQPdf.Next;

namespace HiQPdf_Next_AspNetDemo.Controllers
{
    public class ExcelToPdfController : Controller
    {
        private readonly IWebHostEnvironment m_hostingEnvironment;

        public ExcelToPdfController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            var model = SetViewModel();

            return View(model);
        }


        [HttpPost]
        public async Task<IActionResult> ConvertExcelToPdf(ExcelToPdfViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
                throw new ValidationException(errorMessage);
            }

            // Replace the demo serial number with the serial number received upon purchase
            // to run the converter in licensed mode
            Licensing.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";

            // Create an Excel to PDF converter object with default settings
            ExcelToPdfConverter excelToPdfConverter = new ExcelToPdfConverter();

            // Set whether to keep the original Excel column widths percentage in the generated PDF document
            excelToPdfConverter.KeepColumnWidths = model.KeepColumnWidths;

            // Set whether to keep the original Excel row heights in the generated PDF document
            excelToPdfConverter.KeepRowHeights = model.KeepRowHeights;

            // Set whether to use page settings (size, margins) from the Excel document or the custom settings
            excelToPdfConverter.PdfDocumentOptions.UsePageSettingsFromExcel = model.PdfPageSettingsMode == "FromExcelDocument";

            // Set whether page settings from the first worksheet or from active worksheet are used for all worksheets
            // Has no effect when UsePageSettingsFromExcel is false
            excelToPdfConverter.PdfDocumentOptions.UseFirstWorksheetPageSettings = model.UseFirstWorksheetPageSettings;

            // Set whether to convert only the first worksheet of the workbook or all worksheets
            excelToPdfConverter.PdfDocumentOptions.ConvertOnlyFirstWorksheet = model.ConvertOnlyFirstWorksheet;

            // Set whether each worksheet starts on a new PDF page
            excelToPdfConverter.PdfDocumentOptions.PageBreakBetweenWorksheets = model.PageBreakBetweenWorksheets;

            // Set whether the worksheet title is displayed at the top of each worksheet in the PDF document
            excelToPdfConverter.PdfDocumentOptions.DisplayWorksheetTitle = model.DisplayWorksheetTitle;

            if (!excelToPdfConverter.PdfDocumentOptions.UsePageSettingsFromExcel)
            {
                // Set PDF page size which can be a predefined size like A4 or a custom size in points 
                // Leave it not set to have a default A4 PDF page
                excelToPdfConverter.PdfDocumentOptions.PageSize = SelectedPdfPageSize(model.PdfPageSize);

                // Set PDF page orientation to Portrait or Landscape
                // Leave it not set to have a default Portrait orientation for PDF page
                excelToPdfConverter.PdfDocumentOptions.PageOrientation = SelectedPdfPageOrientation(model.PdfPageOrientation);

                // Set PDF page margins in points or leave them not set to have a PDF page without margins
                excelToPdfConverter.PdfDocumentOptions.Margins.Left = model.LeftMargin;
                excelToPdfConverter.PdfDocumentOptions.Margins.Right = model.RightMargin;
                excelToPdfConverter.PdfDocumentOptions.Margins.Top = model.TopMargin;
                excelToPdfConverter.PdfDocumentOptions.Margins.Bottom = model.BottomMargin;

                // Set the excel viewer zoom percentage
                excelToPdfConverter.PdfDocumentOptions.Zoom = model.ExcelViewerZoom;
            }

            // Set PDF header and footer
            SetHeader(excelToPdfConverter, model);
            SetFooter(excelToPdfConverter, model);

            byte[] inputExcelBytes = null;

            // If an uploaded file exists, use it with priority
            if (model.ExcelFile != null && model.ExcelFile.Length > 0)
            {
                try
                {
                    using var ms = new MemoryStream();
                    await model.ExcelFile.CopyToAsync(ms);
                    inputExcelBytes = ms.ToArray();
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to read the uploaded Excel file", ex);
                }
            }
            else
            {
                // Otherwise, fall back to the URL
                string excelUrl = model.ExcelFileUrl?.Trim();
                if (string.IsNullOrWhiteSpace(excelUrl))
                    throw new Exception("No Excel file provided: upload a file or specify a URL");

                try
                {
                    if (excelUrl.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
                    {
                        string localPath = new Uri(excelUrl).LocalPath;
                        inputExcelBytes = await System.IO.File.ReadAllBytesAsync(localPath);
                    }
                    else
                    {
                        using var httpClient = new System.Net.Http.HttpClient();
                        inputExcelBytes = await httpClient.GetByteArrayAsync(excelUrl);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Could not download the Excel file from URL", ex);
                }
            }

            // The buffer to receive the generated PDF document
            byte[] outPdfBuffer = excelToPdfConverter.ConvertToPdf(inputExcelBytes);

            // Send the PDF file to browser
            FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
            // send as attachment
            fileResult.FileDownloadName = "Excel_to_Pdf.pdf";

            return fileResult;
        }

        private void SetHeader(ExcelToPdfConverter excelToPdfConverter, ExcelToPdfViewModel model)
        {
            bool headerEnabled = model.HeaderEnabled;
            if (!headerEnabled)
                return;

            // Set the header HTML from a URL or from an HTML string
            bool headerHtmlFromUrl = model.HeaderHtmlSource == "Url";
            if (headerHtmlFromUrl)
            {
                string headerUrl = model.HeaderUrl;

                excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.HtmlSourceUrl = headerUrl;
            }
            else
            {
                string headerHtml = model.HeaderHtml;
                string headerHtmlBaseUrl = model.HeaderHtmlBaseUrl;

                excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.Html = headerHtml;
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.HtmlBaseUrl = headerHtmlBaseUrl;
            }

            // Enable automatic height adjustment based on header HTML content
            bool autoSizeHeaderContentHeight = model.AutoSizeHeaderContentHeight;
            excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.AutoSizeContentHeight = autoSizeHeaderContentHeight;

            // Set the minimum and maximum content height used when AutoSizeContentHeight is enabled
            excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.MinContentHeight = model.HeaderMinContentHeight;
            excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.MaxContentHeight = model.HeaderMaxContentHeight;

            // Set a fixed height for the header if AutoResizeHeight is disabled
            if (model.HeaderHeight.HasValue)
            {
                int headerHeight = model.HeaderHeight.Value;
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.Height = headerHeight;
            }

            // If AutoResizeHeight is enabled and both Height and FitHeight are set,
            // the content may be scaled down to fit the specified height
            bool fitHeaderHeight = model.FitHeaderHeight;
            excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.FitHeight = fitHeaderHeight;

            // Enable automatic top margin adjustment in the PDF based on the header
            bool autoResizeTopMargin = model.AutoResizeTopMargin;
            excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.AutoResizePdfMargins = autoResizeTopMargin;

            // Set header visibility on specific PDF pages: first page, odd-numbered pages and even-numbered pages
            excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.ShowInFirstPage = model.ShowHeaderInFirstPage;
            excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.ShowInOddPages = model.ShowHeaderInOddPages;
            excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.ShowInEvenPages = model.ShowHeaderInEvenPages;

            // Reserve space for the header on all pages, regardless of visibility
            // If false, the document will be rendered using print styles instead of screen styles
            excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.ReserveSpaceAlways = model.ReserveHeaderSpace;

            // Optimize the header rendering time by providing a hint if the HTML template contains variables such as { page_number} or { total_pages}
            excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.SkipVariablesParsing = model.SkipHeaderVariablesParsing;

            // Optionally set additional time to wait for the asynchronous header HTML content before rendering
            if (model.HeaderWaitBeforeConvert.HasValue && model.HeaderWaitBeforeConvert.Value > 0)
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlHeader.WaitBeforeConvert = model.HeaderWaitBeforeConvert.Value;
        }

        private void SetFooter(ExcelToPdfConverter excelToPdfConverter, ExcelToPdfViewModel model)
        {
            bool footerEnabled = model.FooterEnabled;
            if (footerEnabled)
            {
                // Set the footer HTML from a URL or from an HTML string
                bool footerHtmlFromUrl = model.FooterHtmlSource == "Url";
                if (footerHtmlFromUrl)
                {
                    string footerUrl = model.FooterUrl;

                    excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.HtmlSourceUrl = footerUrl;
                }
                else
                {
                    string footerHtml = model.FooterHtml;
                    string footerHtmlBaseUrl = model.FooterHtmlBaseUrl;

                    excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.Html = footerHtml;
                    excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.HtmlBaseUrl = footerHtmlBaseUrl;
                }

                // Enable automatic height adjustment based on footer HTML content
                bool autoSizeFooterContentHeight = model.AutoSizeFooterContentHeight;
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.AutoSizeContentHeight = autoSizeFooterContentHeight;

                // Set the minimum and maximum content height used when AutoSizeContentHeight is enabled
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.MinContentHeight = model.FooterMinContentHeight;
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.MaxContentHeight = model.FooterMaxContentHeight;

                // Set a fixed height for the footer if AutoResizeHeight is disabled
                if (model.FooterHeight.HasValue)
                {
                    int footerHeight = model.FooterHeight.Value;
                    excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.Height = footerHeight;
                }

                // If AutoResizeHeight is enabled and both Height and FitHeight are set,
                // the content may be scaled down to fit the specified height
                bool fitFooterHeight = model.FitFooterHeight;
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.FitHeight = fitFooterHeight;

                // Enable automatic bottom margin adjustment in the PDF based on the footer
                bool autoResizeBottomMargin = model.AutoResizeBottomMargin;
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.AutoResizePdfMargins = autoResizeBottomMargin;

                // Set footer visibility on specific PDF pages: first page, odd-numbered pages and even-numbered pages
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.ShowInFirstPage = model.ShowFooterInFirstPage;
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.ShowInOddPages = model.ShowFooterInOddPages;
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.ShowInEvenPages = model.ShowFooterInEvenPages;

                // Reserve space for the footer on all pages, regardless of visibility
                // If false, the document will be rendered using print styles instead of screen styles
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.ReserveSpaceAlways = model.ReserveFooterSpace;

                // Optimize the footer rendering time by providing a hint if the HTML template contains variables such as { page_number} or { total_pages}
                excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.SkipVariablesParsing = model.SkipFooterVariablesParsing;

                // Optionally set additional time to wait for the asynchronous footer HTML content before rendering
                if (model.FooterWaitBeforeConvert.HasValue && model.FooterWaitBeforeConvert.Value > 0)
                    excelToPdfConverter.PdfDocumentOptions.PdfHtmlFooter.WaitBeforeConvert = model.FooterWaitBeforeConvert.Value;
            }
        }

        private PdfPageSize SelectedPdfPageSize(string selectedValue)
        {
            switch (selectedValue)
            {
                case "A0":
                    return PdfPageSize.A0;
                case "A1":
                    return PdfPageSize.A1;
                case "A10":
                    return PdfPageSize.A10;
                case "A2":
                    return PdfPageSize.A2;
                case "A3":
                    return PdfPageSize.A3;
                case "A4":
                    return PdfPageSize.A4;
                case "A5":
                    return PdfPageSize.A5;
                case "A6":
                    return PdfPageSize.A6;
                case "A7":
                    return PdfPageSize.A7;
                case "A8":
                    return PdfPageSize.A8;
                case "A9":
                    return PdfPageSize.A9;
                case "ArchA":
                    return PdfPageSize.ArchA;
                case "ArchB":
                    return PdfPageSize.ArchB;
                case "ArchC":
                    return PdfPageSize.ArchC;
                case "ArchD":
                    return PdfPageSize.ArchD;
                case "ArchE":
                    return PdfPageSize.ArchE;
                case "B0":
                    return PdfPageSize.B0;
                case "B1":
                    return PdfPageSize.B1;
                case "B2":
                    return PdfPageSize.B2;
                case "B3":
                    return PdfPageSize.B3;
                case "B4":
                    return PdfPageSize.B4;
                case "B5":
                    return PdfPageSize.B5;
                case "Flsa":
                    return PdfPageSize.Flsa;
                case "HalfLetter":
                    return PdfPageSize.HalfLetter;
                case "Ledger":
                    return PdfPageSize.Ledger;
                case "Legal":
                    return PdfPageSize.Legal;
                case "Letter":
                    return PdfPageSize.Letter;
                case "Letter11x17":
                    return PdfPageSize.Letter11x17;
                case "Note":
                    return PdfPageSize.Note;
                default:
                    return PdfPageSize.A4;
            }
        }

        private PdfPageOrientation SelectedPdfPageOrientation(string selectedValue)
        {
            return selectedValue == "Portrait" ? PdfPageOrientation.Portrait : PdfPageOrientation.Landscape;
        }

        private ExcelToPdfViewModel SetViewModel()
        {
            var model = new ExcelToPdfViewModel();

            var contentRootPath = System.IO.Path.Combine(m_hostingEnvironment.ContentRootPath, "wwwroot");

            HttpRequest request = ControllerContext.HttpContext.Request;
            UriBuilder uriBuilder = new UriBuilder();
            uriBuilder.Scheme = request.Scheme;
            uriBuilder.Host = request.Host.Host;
            if (request.Host.Port != null)
                uriBuilder.Port = (int)request.Host.Port;
            uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
            uriBuilder.Query = request.QueryString.ToString();

            string currentPageUrl = uriBuilder.Uri.AbsoluteUri;
            string rootUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "ExcelToPdf".Length);

            model.HeaderHtml = System.IO.File.ReadAllText(System.IO.Path.Combine(contentRootPath, "DemoFiles/Html/Header_HTML.html"));
            model.FooterHtml = System.IO.File.ReadAllText(System.IO.Path.Combine(contentRootPath, "DemoFiles/Html/Footer_HTML.html"));
            model.HeaderHtmlBaseUrl = rootUrl + "DemoFiles/Html/";
            model.HeaderUrl = rootUrl + "DemoFiles/Html/Header_HTML.html";
            model.FooterHtmlBaseUrl = rootUrl + "DemoFiles/Html/";
            model.FooterUrl = rootUrl + "DemoFiles/Html/Footer_HTML.html";
            model.ExcelFileUrl = rootUrl + "/DemoFiles/Excel/Excel_Document.xlsx";

            return model;
        }
    }
}

See Also