將 PDF 轉換為 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);
    }
}
$vbLabelText   $csharpLabel

說明:

  • PdfDocument初始化:使用要轉換的 PDF 的檔案名稱初始化PdfDocument物件。 將SomePdfLibrary替換為您實際使用的庫。
  • BinaryData檢索:檢索給定 PDF 的二進位資料(作為位元組數組)。
  • Base64 轉換: Convert.ToBase64String方法用於將位元組陣列轉換為 Base64 字串。 -輸出 Base64 字串:將 Base64 編碼的字串列印到控制台進行驗證。
柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。

準備好開始了嗎?
Nuget 下載 17,012,929 | 版本: 2025.12 剛剛發布