Saltar al pie de página
USANDO IRONPDF
Cómo convertir archivos Excel a PDF en C#

Cómo Convertir Excel a PDF en C# (Tutorial Paso a Paso)

Excel files can be difficult to share because they can be easily altered and are not compatible with all devices and programs. PDFs (Portable Document Format), on the other hand, are universally compatible and cannot be edited without specialized software. For this reason, many businesses require that developers convert Excel files (.xls, .xlsx) to ISO standardized version PDF format programmatically.

There are several reasons why this is important. First, it ensures that the data contained in the Excel workbook cannot be altered. Second, it allows the file to be viewed on any device or program. And finally, it makes it possible to password-protect the file, preventing unauthorized access. Overall, converting Excel files to PDF format is an important way to protect data and ensure its compatibility across all platforms.

Converting Excel to PDF document formats can be a simple task if you have the right tools and knowledge. Let's see how to convert using the IronPDF C# library in .NET Core.

IronPDF: .NET PDF Library

IronPDF is a .NET library that makes it easy to generate, edit, and merge PDF files in C# and VB.NET. With IronPDF, you can create PDF in C# from scratch or convert existing HTML, CSS, and JavaScript files into PDFs. You can also add headers, footers, watermarks, and page numbers to PDF files. If you need to collaborate with others on a project, IronPDF makes it easy to merge multiple PDF files into one.

Throughout this article, IronPDF will be used to show how to convert an Excel document into a PDF document using C# and .NET Core.

Prerequisites

There are some prerequisites to convert an XLSX file to a PDF document.

  1. Visual Studio 2022 (Recommended)
  2. A running .NET application with the latest .NET Framework (Recommended)
  3. Microsoft Office installed
  4. A stable internet connection to install the IronPDF library for the Excel to PDF conversion process

Let's move to the main steps to convert an Excel file to PDF.

Step 1: Export your Excel Workbooks as HTML

To export your Excel file to HTML format, do the following steps:

  1. Launch Microsoft Excel and load the Excel spreadsheets there.

    Convert Excel to PDF in C# (Step-by-Step) Tutorial, Figure 1: Load Excel Spreadsheets Load Excel Spreadsheets

  2. Select "Save As" from the "File" menu.

    Convert Excel to PDF in C# (Step-by-Step) Tutorial, Figure 2: SaveAs Option SaveAs Option

  3. Click on the 'Browse' button and navigate to your desired location. From the File type dropdown, select the 'HTML Page'.

    Convert Excel to PDF in C# (Step-by-Step) Tutorial, Figure 3: File Type Selection File Type Selection

Your Excel file will be converted to an HTML file if you complete the procedures above. The exported HTML file can now be used to convert to PDF.

Step 2: Add IronPDF to your solution

The next step is to install IronPDF in this project using the NuGet Package Manager Console. Click on the Tools from the top menu and select the NuGet Package Manager followed by "Package Manager Console".

Convert Excel to PDF in C# (Step-by-Step) Tutorial, Figure 4: NuGet Package Manager NuGet Package Manager

In the Console, write the following command to install IronPDF.

Install-Package IronPdf

This command will install the latest version of IronPDF in the project.

Step 3: Code Examples to Convert Excel file to PDF

Open the Program.cs file and write the following code fragments to convert the Excel file to PDF using the IronPDF C# library.

Step 3.1: Include IronPDF

Import the IronPDF in the code file to use it in the program.

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

The above code enables IronPDF to take part in the code.

Step 3.2: Instantiate a ChromePdfRenderer Object

Instantiate a ChromePdfRenderer object in the program. It'll enable the use of IronPDF to convert the HTML file to PDF.

var renderer = new ChromePdfRenderer();
var renderer = new ChromePdfRenderer();
Dim renderer = New ChromePdfRenderer()
$vbLabelText   $csharpLabel

Step 3.3: Convert the HTML (Exported from Excel File) to PDF

Use the RenderHtmlFileAsPdf function to convert HTML files to PDFs. In the parameter list, pass the HTML file path. IronPDF will read the contents of the HTML file and convert it into a PDF document.

var document = renderer.RenderHtmlFileAsPdf(@"C:\Users\Administrator\Desktop\Inventory.html");
var document = renderer.RenderHtmlFileAsPdf(@"C:\Users\Administrator\Desktop\Inventory.html");
Dim document = renderer.RenderHtmlFileAsPdf("C:\Users\Administrator\Desktop\Inventory.html")
$vbLabelText   $csharpLabel

IronPDF also supports adding passwords to the PDF file, preventing the PDF file from editing, opening, printing, and other operations. Let's have a look at how to add passwords using IronPDF.

Add Password to PDF File

Use the SecuritySettings property on the PDF document created in the previous step to set a password. It helps to secure the PDF file from data breaches.

document.SecuritySettings.UserPassword = "editable";
document.SecuritySettings.UserPassword = "editable";
document.SecuritySettings.UserPassword = "editable"
$vbLabelText   $csharpLabel

Step 3.4: Save the PDF File

Now, it's time to save the generated PDF file on the local machine by using the following code.

document.SaveAs("C:\\excelToPdf.pdf");
document.SaveAs("C:\\excelToPdf.pdf");
document.SaveAs("C:\excelToPdf.pdf")
$vbLabelText   $csharpLabel

Output PDF File

When you try to open the file, it'll require a password.

Convert Excel to PDF in C# (Step-by-Step) Tutorial, Figure 5: Enter Password for File Enter Password for File

After entering the password, you can see the converted PDF file from an Excel file. IronPDF beautifully converts Excel documents to PDFs while retaining the original formatting.

Convert Excel to PDF in C# (Step-by-Step) Tutorial, Figure 6: Output PDF File Output PDF File

You can see all the worksheets there. You can open any worksheet by clicking on any worksheet name.

Convert Excel to PDF in C# (Step-by-Step) Tutorial, Figure 6: PDF Worksheets PDF Worksheets

Summary

IronPDF is an easy-to-use PDF converter that can be used in C# .NET. In this blog post, you were shown how to convert Excel to PDF using IronPDF. If you want to learn more about the capabilities of IronPDF or see some examples of how it can be used, check out some of the other articles on how to create a PDF file from HTML.

You can start with a free trial of IronPDF, and then purchase IronPDF for as little as $799. Or, if you need more than one Iron Software product, you can buy the Iron Suite bundle of five software programs for the price of two.

Preguntas Frecuentes

¿Por qué es beneficioso para las empresas convertir Excel a PDF?

Convertir archivos Excel a PDF es ventajoso para las empresas porque los PDFs son universalmente compatibles, asegurando que los documentos compartidos mantengan su formato previsto y sean seguros contra ediciones no autorizadas.

¿Cómo puedo convertir Excel a PDF en C# sin perder formato?

Para convertir Excel a PDF en C# sin perder formato, puede usar la biblioteca IronPDF, que le permite renderizar archivos Excel como HTML primero y luego convertirlos a PDF usando el método RenderHtmlFileAsPdf.

¿Cuáles son los pasos necesarios para convertir Excel a PDF usando IronPDF en .NET Core?

Los pasos incluyen exportar el archivo Excel como HTML, instalar la biblioteca IronPDF a través de NuGet y usar la clase ChromePdfRenderer para convertir el HTML a un PDF manteniendo el formato original.

¿Puedo asegurar un PDF creado a partir de un archivo Excel con una contraseña usando C#?

Sí, IronPDF le permite mejorar la seguridad de un PDF estableciendo una contraseña de usuario usando la propiedad SecuritySettings, lo cual ayuda a prevenir el acceso no autorizado.

¿Hay una manera de probar la conversión a PDF en C# antes de comprometerse a comprar una biblioteca?

Sí, IronPDF ofrece una prueba gratuita, permitiéndole explorar sus características y capacidades para la conversión y gestión de PDFs en proyectos C# antes de comprar.

¿Cuáles son los requisitos previos para instalar IronPDF para convertir Excel a PDF?

Para instalar IronPDF y convertir Excel a PDF, necesita Visual Studio 2022, una aplicación .NET con el último .NET Framework, Microsoft Office y una conexión a internet para descargar la biblioteca desde NuGet.

¿La biblioteca IronPDF admite la fusión de múltiples PDFs?

Sí, IronPDF no solo facilita la conversión de Excel a PDF, sino que también proporciona funcionalidad para fusionar varios documentos PDF sin problemas.

¿Cómo puedo asegurarme de que el formato original de Excel se conserve en el PDF?

IronPDF está diseñado para retener el formato original de los archivos Excel durante la conversión al exportar primero el Excel como HTML y luego renderizar el HTML como PDF.

¿Qué método en IronPDF se debe usar para convertir archivos HTML a PDF?

El método RenderHtmlFileAsPdf en IronPDF se usa para convertir archivos HTML, que son exportados desde Excel, en PDFs preservando el formato del documento.

.NET 10: ¿IronPDF admite la conversión de Excel a PDF dentro de un proyecto .NET 10 sin problemas de compatibilidad?

Sí. Según la documentación de IronPDF, IronPDF es totalmente compatible con .NET 10 y ofrece soporte inmediato para todas las versiones modernas de .NET, incluida .NET 10, lo que garantiza una conversión fluida de Excel a PDF sin soluciones especiales.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más