Convertir PDF a Base64

This article was translated from English: Does it need improvement?
Translated
View the article in English
¿Cómo puedo convertir un PDF a Base64?

El objeto PdfDocument no contiene una propiedad directa para obtener Base64. Sin embargo, se puede obtener la matriz de bytes, que luego se puede usar para obtener la cadena Base64.

using System;
using SomePdfLibrary; // Make sure to import the library used for handling PDF files

class Program
{
    static void Main()
    {
        // Create a PdfDocument object for the specified PDF file
        var pdf = new PdfDocument("MyPDF.pdf");

        // Get the binary data (byte array) from the PDF document
        var byteArray = pdf.BinaryData;

        // Convert the byte array to a Base64 string
        var base64Result = Convert.ToBase64String(byteArray);

        // Output the Base64 result
        Console.WriteLine("Base64 of PDF: " + base64Result);
    }
}
using System;
using SomePdfLibrary; // Make sure to import the library used for handling PDF files

class Program
{
    static void Main()
    {
        // Create a PdfDocument object for the specified PDF file
        var pdf = new PdfDocument("MyPDF.pdf");

        // Get the binary data (byte array) from the PDF document
        var byteArray = pdf.BinaryData;

        // Convert the byte array to a Base64 string
        var base64Result = Convert.ToBase64String(byteArray);

        // Output the Base64 result
        Console.WriteLine("Base64 of PDF: " + base64Result);
    }
}
$vbLabelText   $csharpLabel

Explicación:

  • PdfDocument Inicialización: El objeto PdfDocument se inicializa con el nombre del archivo PDF que desea convertir. Reemplace SomePdfLibrary con la biblioteca real que está utilizando.
  • BinaryData Recuperación: Recupera los datos binarios (como una matriz de bytes) del PDF dado.
  • Conversión Base64: El método Convert.ToBase64String se utiliza para convertir la matriz de bytes en una cadena Base64.
  • Cadena Base64 de salida: La cadena codificada en Base64 se imprime en la consola para verificación.
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
¿Listo para empezar?
Nuget Descargas 17,803,474 | Versión: 2026.3 recién lanzado
Still Scrolling Icon

¿Aún desplazándote?

¿Quieres una prueba rápida? PM > Install-Package IronPdf
ejecutar una muestra Mira cómo tu HTML se convierte en PDF.