Convertir les PDF en Base64
Comment puis-je convertir un PDF en Base64 ?
L'objet PdfDocument ne contient pas de propriété directe pour obtenir Base64. Cependant, vous pouvez obtenir le tableau d'octets, qui peut ensuite être utilisé pour obtenir la chaîne 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);
}
}
Imports System
Imports SomePdfLibrary ' Make sure to import the library used for handling PDF files
Friend Class Program
Shared Sub Main()
' Create a PdfDocument object for the specified PDF file
Dim pdf = New PdfDocument("MyPDF.pdf")
' Get the binary data (byte array) from the PDF document
Dim byteArray = pdf.BinaryData
' Convert the byte array to a Base64 string
Dim base64Result = Convert.ToBase64String(byteArray)
' Output the Base64 result
Console.WriteLine("Base64 of PDF: " & base64Result)
End Sub
End Class
Explication :
- Initialisation de
PdfDocument: L'objetPdfDocumentest initialisé avec le nom de fichier du PDF que vous souhaitez convertir. RemplacezSomePdfLibrarypar la bibliothèque que vous utilisez réellement. - Récupération de
BinaryData: Il récupère les données binaires (sous forme de tableau d'octets) du PDF donné. - Conversion en Base64 : La méthode
Convert.ToBase64Stringest utilisée pour convertir le tableau d'octets en une chaîne Base64. - Sortie de la chaîne Base64 : La chaîne encodée Base64 est imprimée sur la console pour vérification.

