SelectPdf for .NET 10 - Convert Excel to Pdf - C# / .NET 10 Sample

This sample shows how to use the SelectPdf Excel to pdf converter to convert an Excel workbook (xlsx, xls, csv and the other formats the converter reads) to pdf, setting a few properties. The conversion runs in-process; no engine is launched.

The sample converts the following Excel workbook, or a workbook you upload:
Test Excel workbook

Excel workbook (optional, xlsx / xls / csv):

Page Setup:

(Document prints every sheet as its own page setup says; Options lays the sheets out on the page size, orientation and margins below.)

Pdf Page Size:


Pdf Page Orientation:


Margins:
pt

Scaling:


Gridlines:


Sheets (names, comma separated; empty converts every sheet):


Add a header
Add page numbers in the footer

One bookmark per sheet

Pdf Standard:


Accessibility (PDF/UA):


Document Title (required by PDF/UA):


Document Language:


Sample code · C#
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class ConvertExcelToPdfModel : PageModel
    {
        public void OnGet()
        {
            DdlPageSetup = "Document";
            DdlPageSize = "A4";
            DdlPageOrientation = "Portrait";
            DdlLayout = "Automatic";
            DdlGridLines = "Automatic";
            ChkSheetBookmarks = true;
            DdlPdfStandard = "Full";
            DdlAccessibility = "None";
            TxtTitle = "SelectPdf - Excel workbook";
            TxtLanguage = "en-US";
            TxtMargins = "0";
        }

        // An uploaded workbook, or nothing - the shipped files/workbook.xlsx is converted then.
        [BindProperty]
        public IFormFile FileExcel { get; set; }

        [BindProperty]
        public string DdlPageSetup { get; set; }

        public List<SelectListItem> PageSetups { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Document", Text = "Document - each sheet's own page setup" },
            new SelectListItem { Value = "Options", Text = "Options - lay out on the page set here" },
        };

        [BindProperty]
        public string DdlPageSize { get; set; }

        public List<SelectListItem> PageSizes { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "A3", Text = "A3" },
            new SelectListItem { Value = "A4", Text = "A4" },
            new SelectListItem { Value = "A5", Text = "A5" },
            new SelectListItem { Value = "Letter", Text = "Letter" },
            new SelectListItem { Value = "Legal", Text = "Legal" },
        };

        [BindProperty]
        public string DdlPageOrientation { get; set; }

        public List<SelectListItem> PageOrientations { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Portrait", Text = "Portrait" },
            new SelectListItem { Value = "Landscape", Text = "Landscape" },
        };

        [BindProperty]
        public string TxtMargins { get; set; }

        [BindProperty]
        public string DdlLayout { get; set; }

        public List<SelectListItem> Layouts { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Automatic", Text = "The sheet's own print scaling" },
            new SelectListItem { Value = "NoScaling", Text = "Actual size" },
            new SelectListItem { Value = "FitSheetOnOnePage", Text = "Fit each sheet on one page" },
            new SelectListItem { Value = "FitAllColumnsOnOnePage", Text = "Fit all columns on one page" },
            new SelectListItem { Value = "FitAllRowsOnOnePage", Text = "Fit all rows on one page" },
        };

        [BindProperty]
        public string DdlGridLines { get; set; }

        public List<SelectListItem> GridLines { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Automatic", Text = "As each sheet's print setting says" },
            new SelectListItem { Value = "Visible", Text = "Draw the gridlines" },
            new SelectListItem { Value = "Hidden", Text = "No gridlines" },
        };

        [BindProperty]
        public string TxtWorksheets { get; set; }

        [BindProperty]
        public bool ChkSheetBookmarks { get; set; }

        [BindProperty]
        public string DdlPdfStandard { get; set; }

        public List<SelectListItem> PdfStandards { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Full", Text = "Full (no standard)" },
            new SelectListItem { Value = "PdfA", Text = "PDF/A-1b" },
            new SelectListItem { Value = "PdfA2B", Text = "PDF/A-2b" },
            new SelectListItem { Value = "PdfA3B", Text = "PDF/A-3b" },
            new SelectListItem { Value = "PdfA4", Text = "PDF/A-4" },
        };

        [BindProperty]
        public string DdlAccessibility { get; set; }

        public List<SelectListItem> Accessibility { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "None", Text = "None" },
            new SelectListItem { Value = "UA1", Text = "PDF/UA-1" },
            new SelectListItem { Value = "UA2", Text = "PDF/UA-2 (PDF 2.0)" },
        };

        [BindProperty]
        public string TxtTitle { get; set; }

        [BindProperty]
        public string TxtLanguage { get; set; }

        [BindProperty]
        public bool ChkHeader { get; set; }

        [BindProperty]
        public bool ChkPageNumbers { get; set; }

        public IActionResult OnPost()
        {
            // read parameters from the webpage
            ExcelPageSetup pageSetup = SampleForm.ParseEnum(DdlPageSetup, ExcelPageSetup.Document);
            PdfPageSize pageSize = SampleForm.ParseEnum(DdlPageSize, PdfPageSize.A4);
            PdfPageOrientation pdfOrientation = SampleForm.ParseEnum(DdlPageOrientation, PdfPageOrientation.Portrait);
            ExcelLayout layout = SampleForm.ParseEnum(DdlLayout, ExcelLayout.Automatic);
            ExcelGridLines gridLines = SampleForm.ParseEnum(DdlGridLines, ExcelGridLines.Automatic);
            PdfStandard pdfStandard = SampleForm.ParseEnum(DdlPdfStandard, PdfStandard.Full);
            PdfUAStandard accessibility = SampleForm.ParseEnum(DdlAccessibility, PdfUAStandard.None);

            int margins = 0;
            try
            {
                margins = Convert.ToInt32(TxtMargins);
            }
            catch { }

            // instantiate an excel to pdf converter object
            ExcelToPdf converter = new ExcelToPdf();

            // set converter options: the page setup policy decides whether the page size,
            // orientation and margins below are applied (Options) or every sheet is printed as
            // its own page setup says (Document) - the margins and the bands apply either way
            converter.Options.PageSetup = pageSetup;
            converter.Options.PdfPageSize = pageSize;
            converter.Options.PdfPageOrientation = pdfOrientation;
            converter.Options.MarginLeft = margins;
            converter.Options.MarginRight = margins;
            converter.Options.MarginTop = margins;
            converter.Options.MarginBottom = margins;

            // how the sheets are scaled onto their pages, the gridlines, the sheets converted
            // (by name, comma separated - empty converts every visible sheet) and one outline
            // entry per sheet
            converter.Options.Layout = layout;
            converter.Options.GridLines = gridLines;
            converter.Options.Worksheets = TxtWorksheets ?? string.Empty;
            converter.Options.SheetBookmarks = ChkSheetBookmarks;
            converter.Options.PdfStandard = pdfStandard;

            // accessibility: the sheets' tables, charts, pictures and links become the logical
            // structure of the pdf; a declared standard needs a title and a language (PDF/UA-2 is
            // written as PDF 2.0 and combines with PDF/A-4 only)
            converter.Options.AccessibilityStandard = accessibility;
            converter.Options.Title = TxtTitle;
            converter.Options.Language = TxtLanguage;

            // a text header band and a page-number footer; a PdfExcelSection could carry a workbook
            // as the band instead, and a PdfHtmlSection an html one. A width of -1 spans the whole
            // band, so the centered texts stay centered whatever the page size and margins.
            if (ChkHeader)
            {
                converter.Options.DisplayHeader = true;
                converter.Header.Height = 40;
                PdfTextSection headerText = new PdfTextSection(0, 16, -1, "Converted with SelectPdf Excel to Pdf",
                    PdfFont.CreateStandardFont(PdfStandardFont.HelveticaBold, 10), new PdfColor(44, 62, 80));
                headerText.HorizontalAlign = PdfTextHorizontalAlign.Center;
                converter.Header.Add(headerText);
            }
            if (ChkPageNumbers)
            {
                converter.Options.DisplayFooter = true;
                converter.Footer.Height = 30;
                PdfTextSection pageNumbers = new PdfTextSection(0, 8, -1, "Page {page_number} of {total_pages}",
                    PdfFont.CreateStandardFont(PdfStandardFont.Helvetica, 9), new PdfColor(80, 80, 80));
                pageNumbers.HorizontalAlign = PdfTextHorizontalAlign.Center;
                converter.Footer.Add(pageNumbers);
            }

            // convert the uploaded workbook, or the sample one shipped with the application
            PdfDocument doc;
            if (FileExcel != null && FileExcel.Length > 0)
            {
                using (MemoryStream uploaded = new MemoryStream())
                {
                    FileExcel.CopyTo(uploaded);
                    uploaded.Position = 0;
                    // the format is taken from the uploaded file's name, since a stream carries none
                    ExcelFormat format = ExcelFormatFromFileName(FileExcel.FileName);
                    doc = converter.ConvertStream(uploaded, format);
                }
            }
            else
            {
                string excelFile = Path.Combine(Startup.ServerPath, "wwwroot", "files", "workbook.xlsx");
                doc = converter.ConvertFile(excelFile);
            }

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }

        private static ExcelFormat ExcelFormatFromFileName(string fileName)
        {
            switch ((Path.GetExtension(fileName) ?? string.Empty).ToLowerInvariant())
            {
                case ".xlsx": return ExcelFormat.Xlsx;
                case ".xlsm": return ExcelFormat.Xlsm;
                case ".xltx": return ExcelFormat.Xltx;
                case ".xltm": return ExcelFormat.Xltm;
                case ".xls": return ExcelFormat.Xls;
                case ".xlt": return ExcelFormat.Xlt;
                case ".csv": return ExcelFormat.Csv;
                case ".tsv": return ExcelFormat.Tsv;
                default: return ExcelFormat.Automatic;
            }
        }
    }
}