将 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);
}
}
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
- PdfWriter:此对象负责写入PDF文件。它作用于文件路径,并写入有效PDF文档所需的结构。
PdfDocument初始化:PdfDocument对象使用您要转换的PDF文件名进行初始化。 将SomePdfLibrary替换为您正在使用的实际库。BinaryData检索: 它检索给定PDF的二进制数据(作为字节数组)。- Base64 转换: 使用
Convert.ToBase64String方法将字节数组转换为Base64字符串。 - 输出 Base64 字符串: 将 Base64 编码字符串打印到控制台以供验证。
准备开始了吗?
Nuget 下载 20,296,129 | 版本: 2026.7 刚刚发布

