Saltar al pie de página
USANDO IRONPDF
Cómo crear un archivo PDF a partir de una matriz de bytes en C#

Guardar Array de Bytes a PDF en C# (Ejemplo de Código)

This guide will explore the process of converting a byte array into a PDF file using the robust capabilities of the IronPDF .NET library. This transformation is crucial for developers who need to work with PDF files within their .NET applications.

Topics Covered in Tutorial

The following topics will be covered in this tutorial:

  • IronPDF
  • Steps to Create PDF Files Programmatically
  • Step 1: Create a C# Project
  • Step 2: Install the IronPDF Library
    • Method 1: NuGet Package Manager Console
    • Method 2: Using the DLL File
  • Step 3: Add the IronPDF Namespace
  • Step 4: Convert Byte Array to PDF File
    • Output
  • Conclusion


IronPDF: C# PDF Library

IronPDF is a .NET library that makes reading, manipulating, and writing PDF documents easy. You can use it in your .NET projects for desktop and Web Applications. IronPDF is available for free for development purposes. This library allows you to convert HTML to PDF, extract text from a PDF, and more. IronPDF is a lightweight .NET PDF library designed specifically with web developers in mind. It is written entirely in C#. IronPDF contains an extensive set of functions that can be used to work with PDF files in a programming environment. Functions are created to improve the workflow and provide access to every aspect of PDF. These include creating, opening, deleting, adding pages, and extracting text from PDF documents. The IronPDF library has many useful features:

Let's start with how to use the IronPDF library to convert the byte array to a PDF file.

Steps to Convert Byte Array to PDF

Starting with opening Visual Studio, select any C# application template according to your project needs. For this quick tutorial, the Console Application template will be used. You can modify the already existing C# project file.

Step 1: Create a C# Project

Use the latest version of Visual Studio for creating the C# project. Follow the provided steps to create a C# project.

  • Open the Visual Studio on your machine.
  • Create a C# Console Application or modify an already existing C# application.
  • Give an appropriate name according to your project.
  • Select the .NET Framework 6.0, the latest framework that comes with long support. You can choose any other framework according to requirements but the latest version is strongly recommended.

By following the above steps, a C# project will be created. Now it's time to install the IronPDF library.

Step 2: Install the IronPDF Library

IronPDF is easy to install too. You get a fast and efficient installation process, cutting down development time and removing the confusion that usually accompanies it.

Method 1: NuGet Package Manager Console

Installing the IronPDF Library with Package Manager Console is very easy. Once you have the console open, type the following command, hit enter and it will be done!

Install-Package IronPdf

Save Byte Array to PDF C# (Code Example), Figure 1: The progress of installing IronPDF in the NuGet Package Manager Console The progress of installing IronPDF in the NuGet Package Manager Console

Method 2: Using a DLL file

To facilitate a more seamless installation process for this library and to give you a good understanding of how to use it, downloading the DLL file from the website directly is also recommended. Installation instructions can be found on this Installation Guide.

Step 3: Add the IronPDF Namespace

Although IronPDF is essential for this project, it is necessary to import its namespace into every code file to use it. To do that, add the following line of code at the top of each file:

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

Step 4: Convert Byte Array to PDF Document

As IronPDF is ready to use, adding the following code into your program file will help to convert byte array to PDF file:

using IronPdf;
using System.Text;

// Converting an array of bytes into a PDF file.

byte[] byteArray = { 84, 104, 105, 115, 32, 105, 115, 32, 98, 121, 116, 101, 32, 97, 114, 114, 97, 121 };

// Convert the byte array into a string using ASCII encoding
string data = Encoding.ASCII.GetString(byteArray);

// Create an HTML string with the data
string HTML = $"<h1>{data}</h1>";

// Initialize PDF renderer
var renderer = new IronPdf.ChromePdfRenderer();

// Render HTML to PDF
using var pdf = renderer.RenderHtmlAsPdf(HTML);

// Save the PDF file
pdf.SaveAs("bytearray.pdf");
using IronPdf;
using System.Text;

// Converting an array of bytes into a PDF file.

byte[] byteArray = { 84, 104, 105, 115, 32, 105, 115, 32, 98, 121, 116, 101, 32, 97, 114, 114, 97, 121 };

// Convert the byte array into a string using ASCII encoding
string data = Encoding.ASCII.GetString(byteArray);

// Create an HTML string with the data
string HTML = $"<h1>{data}</h1>";

// Initialize PDF renderer
var renderer = new IronPdf.ChromePdfRenderer();

// Render HTML to PDF
using var pdf = renderer.RenderHtmlAsPdf(HTML);

// Save the PDF file
pdf.SaveAs("bytearray.pdf");
Imports IronPdf
Imports System.Text

' Converting an array of bytes into a PDF file.

Private byteArray() As Byte = { 84, 104, 105, 115, 32, 105, 115, 32, 98, 121, 116, 101, 32, 97, 114, 114, 97, 121 }

' Convert the byte array into a string using ASCII encoding
Private data As String = Encoding.ASCII.GetString(byteArray)

' Create an HTML string with the data
Private HTML As String = $"<h1>{data}</h1>"

' Initialize PDF renderer
Private renderer = New IronPdf.ChromePdfRenderer()

' Render HTML to PDF
Private pdf = renderer.RenderHtmlAsPdf(HTML)

' Save the PDF file
pdf.SaveAs("bytearray.pdf")
$vbLabelText   $csharpLabel

The above code converts the byte array to PDF. At first, convert the given byte array to a string using the ASCII.GetString function. Then, create an HTML string using the extracted data. After that, initiate ChromePdfRenderer and call the RenderHtmlAsPdf function to convert PDF files and create a new document.

Now, save the resultant PDF file document in the local system by using the SaveAs function.

Output

Save Byte Array to PDF C# (Code Example), Figure 2: The output PDF file from the byte array The output PDF file from the byte array

This is the generated PDF file contents.

Conclusion

This article demonstrated how to easily save a Byte Array from PDF files using the IronPDF .NET PDF library. This was accomplished by only writing a few lines of code and with a high percentage of accuracy. Additionally, IronPDF also has many useful features such as HTML to PDF conversion, PDF formatting tools, and numerous more core PDF features that are imperative for PDF editing. IronPDF also eliminates the dependency on Adobe Acrobat.

IronPDF is free for development purposes and also offers a free trial for production testing. IronPDF provides a variety of pricing plans that you can get according to your needs. The price of IronPDF is relatively significantly less than its competitors. With pricing varying from individual to large companies, it proves to be a compelling purchase with impressive performance.

Save Byte Array to PDF C# (Code Example), Figure 3: The pricing plan for Iron Software's Suite The pricing plan for Iron Software's Suite

In addition, Iron Software offers a suite of five Iron Software packages for the price of just two. Please visit this Licensing Information Page, to get more details.

Preguntas Frecuentes

¿Cómo convierto una matriz de bytes en un archivo PDF usando C#?

Puedes convertir una matriz de bytes en un archivo PDF usando la biblioteca IronPDF utilizando la clase ChromePdfRenderer. Primero, convierte la matriz de bytes a una cadena usando codificación ASCII, crea una cadena HTML, y luego renderízala a PDF usando IronPDF.

¿Qué pasos se necesitan para configurar IronPDF en un proyecto de Visual Studio?

Para configurar IronPDF en un proyecto de Visual Studio, descarga la biblioteca IronPDF, crea un nuevo proyecto, instala la biblioteca a través del Administrador de Paquetes NuGet con Install-Package IronPdf, y añade el espacio de nombres de IronPDF incluyendo using IronPdf; en tus archivos de código.

¿Cómo puedo asegurar la codificación correcta al convertir matrices de bytes a cadenas en C#?

Al convertir matrices de bytes a cadenas para la generación de PDF en C#, usa la codificación ASCII para transformar con precisión el contenido de la matriz de bytes en un formato de cadena legible antes de convertirlo a un PDF usando IronPDF.

¿Cuáles son algunas capacidades de la biblioteca IronPDF?

IronPDF ofrece capacidades como conversión de HTML a PDF, extracción de texto, agregar marcas de agua y renderizar documentos PDF. Está diseñado para integrarse sin problemas en aplicaciones .NET, proporcionando robustas características de manipulación de PDF.

¿Puede IronPDF usarse para la conversión de HTML a PDF con estilo CSS?

Sí, IronPDF puede convertir HTML a PDF mientras soporta el estilo CSS. Esta funcionalidad es particularmente útil para desarrolladores que buscan generar documentos PDF a partir de contenido web con estilo enriquecido.

¿Hay una prueba gratuita disponible para IronPDF?

IronPDF ofrece una prueba gratuita para pruebas de producción. Esto permite a los desarrolladores explorar sus características y funcionalidades antes de comprometerse a una compra.

¿Qué hace que IronPDF sea una opción adecuada para desarrolladores .NET?

IronPDF es una opción adecuada para desarrolladores .NET debido a su facilidad de instalación, características completas de PDF, y su rentabilidad en comparación con los competidores. Su funcionalidad está diseñada para integrarse suavemente dentro de aplicaciones .NET.

¿Cómo puedo solucionar problemas comunes al usar IronPDF?

Para solucionar problemas comunes con IronPDF, consulta la documentación completa proporcionada por IronPDF, explora el código de ejemplo y contacta a su equipo de servicio al cliente para soporte técnico.

¿Cuáles son las ventajas de usar IronPDF sobre Adobe Acrobat para la generación de PDF?

IronPDF es ventajoso sobre Adobe Acrobat para la generación de PDF debido a sus características amigables para el desarrollo, rentabilidad y la capacidad de integrarse directamente en aplicaciones .NET sin la necesidad de software separado.

¿IronPDF es compatible con .NET 10? ¿Hay alguna consideración especial que deba tenerse en cuenta al usarlo con proyectos .NET 10?

Sí, IronPDF es totalmente compatible con .NET 10 y está diseñado para funcionar directamente en proyectos .NET 10 sin necesidad de soluciones alternativas personalizadas. Es compatible con los principales tipos de proyectos, como entornos web, de escritorio, de consola y en la nube. Para usarlo en un proyecto .NET 10, simplemente instálelo mediante NuGet y haga referencia al paquete IronPDF; las mismas API utilizadas en versiones anteriores de .NET funcionarán a la perfección. Para un rendimiento óptimo, aproveche las funciones de .NET 10, como async/await y el recorte, según sea necesario.

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