C# .NET Convert Excel to PDF

Converting Excel files to PDF is a crucial task for anyone looking to share spreadsheet data in a secure, consistent, and universally accessible format. Whether you are generating financial reports, creating invoices, or sharing analytical data, PDFs ensure that your document's layout and formatting remain intact across all devices and platforms. Unlike Excel files, which require compatible software to open, PDFs are universally viewable without any dependency.

This guide provides a comprehensive overview of how to efficiently convert Excel files to PDF in C# using a .NET Excel library – Spire.XLS for .NET. You will learn both basic and advanced conversion techniques, including how to export specific sheets or cell ranges, customize page setup, secure converted PDFs with passwords, generate PDF/A-compliant files, and more.

Table of Contents

Why Convert Excel to PDF

Converting Excel files to PDF offers several key advantages:

  • Preserved Layout and Formatting: PDF maintains the original structure and formatting of your Excel file, ensuring consistent appearance across devices.
  • Cross-Platform Accessibility: PDF is universally compatible, viewable on any device or operating system without requiring Excel or other spreadsheet software.
  • Enhanced Security: PDF files can be encrypted, digitally signed, and restricted to prevent unauthorized access, copying, or editing.

C# .NET Excel to PDF Conversion Library

Spire.XLS for .NET is a comprehensive Excel library that enables seamless conversion of Excel files to PDF within .NET applications without the need for Microsoft Office. It provides developers with full control over how the content is rendered and ensures that the layout and formatting are preserved during the conversion process.

Install Spire.XLS for .NET

Before starting the conversion process, install Spire.XLS for .NET using one of the following methods:

  • Option 1: Install via NuGet (Recommended)
Install-Package Spire.XLS
  • Option 2: Manually Add DLLs to Your Project
    • Download the Spire.XLS package and extract the files.
    • In Visual Studio, right-click References > Add Reference > Browse, then select the appropriate Spire.Xls.dll based on your target framework.

Basic Excel to PDF Conversion

Converting an Excel file to PDF with Spire.XLS is simple and requires only a few lines of code. The following example demonstrates how to load an Excel file and save it as a PDF:

  • C#
using Spire.Xls;

namespace ExcelToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load an Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

            // Save the Excel file to PDF
            workbook.SaveToFile("Output.pdf", FileFormat.PDF);
            // Dispose resources
            workbook.Dispose();
        }
    }
}

C# .NET Convert XLS or XLSX to PDF

Advanced Excel to PDF Conversion Features

In addition to basic conversion, Spire.XLS for .NET provides advanced options for customized Excel-to-PDF conversions, including:

  • Export specific sheet or cell range as PDF.
  • Fit sheet to one page.
  • Adjust page setup options (e.g., margins, orientation, paper size) for customized PDF output.
  • Secure the converted PDF with password.
  • Generate PDF/A-compliant files for long-term preservation.

Export Specific Sheet or Cell Range as PDF

Sometimes, you may want to export only a specific sheet or range of cells from an Excel file to PDF. Here's how to do that:

  • C#
using Spire.Xls;

namespace WorksheetOrCellRangeToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load the Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Set the print area to a specific cell range
            // Comment this line out if you need to export the entire worksheet as a PDF
            sheet.PageSetup.PrintArea = "B1:E6";

            // Save the cell range as a PDF
            sheet.SaveToPdf("CellRange.pdf");
            // Dispose resources
            workbook.Dispose();
        }
    }
}

Fit Sheet to One Page

Spire.XLS allows you to fit the content of a sheet to one page, which is particularly useful for printing or distributing concise reports.

  • C#
using Spire.Xls;

namespace FitWorksheetToOnePage
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load the Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

            // Fit every worksheet in the workbook to one page
            workbook.ConverterSetting.SheetFitToPage = true;

            // Save the Excel file to PDF
            workbook.SaveToFile("FitToOnePage.pdf", FileFormat.PDF);
            // Dispose resources
            workbook.Dispose();
        }
    }
}

Adjust Page Setup for Customized PDF Output

Before converting an Excel worksheet to PDF, you can adjust page setup options such as margins, paper size, orientation, and gridline visibility. This ensures the final PDF is accurately formatted to meet your presentation requirements.

  • C#
using Spire.Xls;

namespace AdjustPageSetup
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load the Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Adjust page setup settings
            // Set page orientation
            sheet.PageSetup.Orientation = PageOrientationType.Landscape;
            // Set paper size
            sheet.PageSetup.PaperSize = PaperSizeType.PaperA4;
            // Set margins
            sheet.PageSetup.LeftMargin = 0.5;
            sheet.PageSetup.RightMargin = 0.5;
            sheet.PageSetup.TopMargin = 0.5;
            sheet.PageSetup.BottomMargin = 0.5;
            // Display Gridlines
            sheet.PageSetup.IsPrintGridlines = true;

            // Save the worksheet as a PDF
            sheet.SaveToPdf("CustomPageSetup.pdf");
            // Dispose resources
            workbook.Dispose();
        }
    }
}

Secure the Converted PDF with Password

You can secure the converted PDF by applying password protection. This ensures that unauthorized users cannot access or modify the document.

  • C#
using Spire.Xls;
using Spire.Xls.Pdf.Security;

namespace SecurePdfWithPassword
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load the Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

            // Set the open and permission passwords for the converted PDF
            workbook.ConverterSetting.PdfSecurity.Encrypt("openPassword", "persmissionPassword", PdfPermissionsFlags.Print, PdfEncryptionKeySize.Key128Bit);

            // Save the Excel file to PDF
            workbook.SaveToFile("SecurePdf.pdf", FileFormat.PDF);
            // Dispose resources
            workbook.Dispose();
        }
    }
}

Generate PDF/A-compliant Files

If you need to archive your documents for long-term storage or ensure they meet certain accessibility standards, you can generate PDF/A-compliant files from Excel.

  • C#
using Spire.Xls;
using Spire.Xls.Pdf;

namespace ExcelToPdfA
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load the Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

            // Set the compliance for the converted PDF
            workbook.ConverterSetting.PdfConformanceLevel = PdfConformanceLevel.Pdf_A1A;

            // Save the Excel file to PDF
            workbook.SaveToFile("PdfA_Compliant.pdf", FileFormat.PDF);
            // Dispose resources
            workbook.Dispose();
        }
    }
}

FAQs

Q1: Can I convert a password-protected Excel file to PDF?

Yes, you can load password-protected Excel files by providing the password before loading:

  • C#
Workbook workbook = new Workbook();
workbook.OpenPassword = "ExcelPassword";
workbook.LoadFromFile("ProtectedExcel.xlsx");
workbook.SaveToFile("Output.pdf", FileFormat.PDF);

Q2: Is Spire.XLS compatible with .NET Core?

Yes, Spire.XLS supports .NET Framework, .NET Core, and .NET Standard.

Q3: Can I batch convert multiple Excel files to PDF?

Yes, you can batch convert multiple Excel files to PDF using a loop:

  • C#
string[] files = Directory.GetFiles("ExcelFolder", "*.xlsx");
foreach (string file in files)
{
    Workbook workbook = new Workbook();
    workbook.LoadFromFile(file);
    string outputPath = Path.ChangeExtension(file, ".pdf");
    workbook.SaveToFile(outputPath, FileFormat.PDF);
}

Q4: Can I convert multiple Excel files to a single PDF?

Yes, you can combine multiple Excel files into a single workbook and then save them as a single PDF:

  • C#
Workbook combinedWorkbook = new Workbook();
combinedWorkbook.Worksheets.Clear();
foreach (string file in Directory.GetFiles("ExcelFolder", "*.xlsx"))
{
    Workbook tempWorkbook = new Workbook();
    tempWorkbook.LoadFromFile(file);
    foreach (Worksheet sheet in tempWorkbook.Worksheets)
    {
        combinedWorkbook.Worksheets.AddCopy(sheet);
    }
}
combinedWorkbook.SaveToFile("Combined.pdf", FileFormat.PDF);

Q5: Why does my converted PDF look different from the Excel file?

This issue could be due to missing fonts on the system. Make sure that all fonts used in the Excel file are installed on the machine performing the conversion.

Conclusion

Spire.XLS for .NET provides a powerful and flexible solution for converting Excel files to PDF in C#. Whether you need simple conversions or advanced features—such as exporting specific sheets or cell ranges, customizing page setup, applying password protection to the converted PDF, or generating PDF/A-compliant files—Spire.XLS offers a comprehensive set of tools to meet all your requirements. By following the steps outlined in this guide, you can easily integrate Excel-to-PDF conversion capabilities into your .NET applications.

Get a Free License

To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.

Superscript and subscript are formatting styles that allow you to display characters or numerals above or below the regular text baseline respectively. By utilizing these formatting styles, you can emphasize certain elements, denote exponents, powers, chemical formulas, or mathematical equations, and present data in a more visually appealing and informative manner. In this article, we will demonstrate how to apply superscript and subscript styles in Excel in C# and VB.NET using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Apply Superscript and Subscript in Excel in C# and VB.NET

To apply the superscript or subscript style to specific characters in a cell, you need to create a custom font, enable the superscript or subscript property of the font, and then assign the custom font to the specific characters within the cell. The detailed steps are as follows:

  • Create a Workbook object.
  • Get a specific worksheet using Workbook.Worksheets[int index] property.
  • Get a specific cell using Worksheet.Range[string name] property and add rich text to the cell using CellRange.RichText.Text property.
  • Create a custom font using Workbook.CreateFont() method.
  • Enable the subscript property of the font by setting ExcelFont.IsSubscript property to true.
  • Assign the custom font to specific characters of the rich text in the cell using CellRange.RichText.SetFont() method.
  • Get a specific cell using Worksheet.Range[string name] property and add rich text to the cell using CellRange.RichText.Text property.
  • Create a custom font using Workbook.CreateFont() method.
  • Enable the superscript property of the font by setting ExcelFont.IsSuperscript property to true.
  • Assign the custom font to specific characters of the rich text in the cell using CellRange.RichText.SetFont() method.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;
using System.Drawing;

namespace ApplySuperscriptAndSubscript
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Add text to specific cells
            sheet.Range["B2"].Text = "This is an example of subscript:";
            sheet.Range["D2"].Text = "This is an example of superscript:";

            //Add rich text to a specific cell
            CellRange range = sheet.Range["B3"];
            range.RichText.Text = "an = Sn - Sn-1";

            //Create a custom font
            ExcelFont font = workbook.CreateFont();
            //Enable the subscript property of the font
            font.IsSubscript = true;
            //Set font color
            font.Color = Color.Green;
            //Assign the font to specific characters of the rich text in the cell
            range.RichText.SetFont(6, 6, font);
            range.RichText.SetFont(11, 13, font);

            //Add rich text to a specific cell
            range = sheet.Range["D3"];
            range.RichText.Text = "a2 + b2 = c2";

            //Create a custom font
            font = workbook.CreateFont();
            //Enable the superscript property of the font
            font.IsSuperscript = true;
            //Assign the font to specific characters of the rich text in the cell
            range.RichText.SetFont(1, 1, font);
            range.RichText.SetFont(6, 6, font);
            range.RichText.SetFont(11, 11, font);

            //Auto-fit column widths
            sheet.AllocatedRange.AutoFitColumns();

            //Save the result file
            workbook.SaveToFile("ApplySubscriptAndSuperscript.xlsx", ExcelVersion.Version2013);
            workbook.Dispose();
        }
    }
}

C#/VB.NET: Apply Superscript and Subscript in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Textboxes in Microsoft Word are versatile tools that enhance document layout and design. They allow users to position text independently of the main text flow, making it easier to create visually appealing documents. In some cases, you may need to extract text from textboxes for repurposing, or update the text inside a textbox to ensure clarity and relevance.

In this article, you will learn how to extract or update text in a textbox in a Word document using C# with Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Extract Text from Textbox in a Word Document

Using Spire.Doc for .NET, you can access a specific text box in a document with the Document.TextBoxes[index] property. Iterate through the text box's child objects to check if each one is a paragraph or a table. For paragraphs, retrieve the text using the Paragraph.Text property. For tables, loop through the cells to extract text from each cell.

The steps to extract text from a textbox in a Word document are as follows:

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Get a specific textbox using Document.TextBoxes[index] property
  • Iterate through the child objects of the textbox.
  • Determine if a child object if a paragraph. If yes, get the text from the paragraph using Paragraph.Text property.
  • Determine if a child object if a table. If yes, get the text from the table using ExtractTextFromTable() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace ExtractTextFromTextbox
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Load a Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

            // Get a specific textbox
            TextBox textBox = document.TextBoxes[0];

            // Create a StreamWriter to write extracted text to a txt file
            using (StreamWriter sw = File.CreateText("result.txt"))
            {
                // Iterate though child objects of the textbox
                foreach (DocumentObject objt in textBox.ChildObjects)
                {
                    // Determine if the child object is a paragraph
                    if (objt.DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        // Write paragraph text to the txt file
                        sw.Write((objt as Paragraph).Text);
                    }

                    // Determine if the child object is a table
                    if (objt.DocumentObjectType == DocumentObjectType.Table)
                    {
                        // Extract text from table to the txt file
                        ExtractTextFromTable(objt as Table, sw);
                    }
                }

            }
 
        }

        // Extract text from a table
        static void ExtractTextFromTable(Table table, StreamWriter sw)
        {
            for (int i = 0; i < table.Rows.Count; i++)
            {
                TableRow row = table.Rows[i];
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    TableCell cell = row.Cells[j];
                    foreach (Paragraph paragraph in cell.Paragraphs)
                    {
                        sw.Write(paragraph.Text);
                    }
                }
            }
        }
    }
}

C#: Extract or Update Text in Textbox in Word

Update a Textbox in a Word Document

To update a text box, first clear its existing content using the TextBox.ChildObjects.Clear() method. Then, add a new paragraph and set its text.

The steps to update a textbox in a Word document are as follows:

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Get a specific textbox using Document.TextBoxes[index] property
  • Remove existing content of the textbox using TextBox.ChildObjects.Clear() method.
  • Add a paragraph to the textbox using TextBox.Body.AddParagraph() method.
  • Add text to the paragraph using Paragraph.AppendText() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace UpdateTextbox
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Load a Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

            // Get a specific textbox
            TextBox textBox = document.TextBoxes[0];

            // Remove child objects of the textbox
            textBox.ChildObjects.Clear();

            // Add a new paragraph to the textbox
            Paragraph paragraph = textBox.Body.AddParagraph();

            // Set line spacing
            paragraph.Format.LineSpacing = 15f;

            // Add text to the paragraph
            TextRange textRange = paragraph.AppendText("The text in this textbox has been updated.");

            // Set font size
            textRange.CharacterFormat.FontSize = 15f;

            // Save the document to a different Word file
            document.SaveToFile("UpdateTextbox.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }

    }

}

C#: Extract or Update Text in Textbox in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

page 271