Convert PDF to Base64

This article was translated from English: Does it need improvement?
Translated
View the article in English
如何將 PDF 轉換為 Base64?

PdfDocument 對象不包含直接獲取 Base64 的屬性。然而,您可以獲取字節數組,然後用於獲取 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
$vbLabelText   $csharpLabel

說明:

  • PdfDocument 初始化: 您想要轉換的 PDF 的文件名用於初始化 PdfDocument 對象。 將 SomePdfLibrary 替換為您正在使用的實際函式庫。
  • BinaryData 檢索: 它會檢索指定 PDF 的二進制數據(作為字節數組)。
  • Base64 轉換: 使用 Convert.ToBase64String 方法將字節數組轉換為 Base64 字符串。
  • 輸出 Base64 字符串: 將 Base64 編碼的字符串打印到控制台進行驗證。
Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 16,154,058 | 版本: 2025.11 剛剛發布