Convert PDF to Base64
How can I convert a PDF to Base64?
The PdfDocument
object doesn't contain a direct property to get Base64. However, you can get the byte array, which can then be used to obtain the Base64 string.
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
Explanation:
PdfDocument
Initialization: ThePdfDocument
object is initialized with the file name of the PDF you want to convert. ReplaceSomePdfLibrary
with the actual library you are using.BinaryData
Retrieval: It retrieves the binary data (as a byte array) of the given PDF.- Base64 Conversion: The
Convert.ToBase64String
method is used to convert the byte array into a Base64 string. - Output Base64 String: The Base64 encoded string is printed to the console for verification.