跳過到頁腳內容
使用IRONPDF

如何在 C# 中合併兩個 PDF 位元組數組

在現代 C# 應用程式中,處理以位元組陣列形式儲存的 PDF 文件是一種常見需求。 無論是從數據庫檢索 PDF 文件、從 Web 服務接收文件,還是在內存中處理它們,將多個 PDF 文件合併為一個無需儲存到磁碟的單一 PDF 是必不可少的。

IronPDF 的直觀 API 讓這一過程變得非常簡單。 您可以輕鬆地合併兩個或多個 PDF 文件,達成創建合併 PDF 作為單一 PDF 輸出的需求。 請跟隨我們一起了解如何在 C# 中合併 PDF 位元組陣列以及完成此任務的不同方法。

甚麼是 PDF 位元組陣列及為什麼要合併它們?

位元組陣列基本上是表示記憶體中的 PDF 文件的原始二進位數據。 在 C# 中處理 PDF 文件時,經常會遇到 PDF 文件以位元組陣列的形式存在,而不是磁碟上的物理文件的情況。 這在從數據庫檢索以二進制數據儲存的文件或從伺服器通過 REST API 接收 PDF 文件時尤其常見。

簡單地連接兩個 PDF 位元組陣列是行不通的——與文本文件不同,PDF 文件具有包括標頭、交叉引用表和特定格式的複雜內部結構。 如果您只是嘗試連接位元組,肯定會遇到錯誤。 您需要一個合適的 PDF 庫來解析這些位元組陣列並正確地合併它們。 IronPDF 處理了所有這些複雜性,允許您僅用幾行程式碼就可以合併 PDF 文件。 這是該庫幫助您了解和解決的核心問題。

如何設置 IronPDF 來進行 PDF 合併?

使用 IronPDF 很簡單。 首先,在專案中安裝 IronPDF 的 NuGet 套件:

Install-Package IronPdf

安裝後,將以下命名空間添加到您的 C# 文件中:

using IronPdf;
using System.IO;
using System.Collections.Generic;
using IronPdf;
using System.IO;
using System.Collections.Generic;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

了解系統和路徑需求以正確處理文件非常重要。 我們可以將這段程式碼用於 ASP 應用程式或桌面應用程式。

如何在 C# 中合併兩個 PDF 位元組陣列:圖 1 - IronPDF NuGet 安裝頁面

如何使用 IronPDF 合併兩個 PDF 文件位元組陣列?

以下是一個完整示例,演示如何將兩個 C# 中的 PDF 位元組陣列合併為單一 PDF:

// Simulate two PDF byte arrays (in practice, these come from a database or API)
byte[] pdfBytes1 = File.ReadAllBytes("document1.pdf");
byte[] pdfBytes2 = File.ReadAllBytes("document2.pdf");

// Create PdfDocument objects from byte arrays
var pdf1 = new PdfDocument(pdfBytes1);
var pdf2 = new PdfDocument(pdfBytes2);

// Merge the two PDF documents
PdfDocument combinedPdf = PdfDocument.Merge(pdf1, pdf2);

// Convert the combined PDF back to byte array
byte[] mergedPdfBytes = combinedPdf.BinaryData;

// Save the merged PDF (optional)
File.WriteAllBytes("merged.pdf", mergedPdfBytes);
// Simulate two PDF byte arrays (in practice, these come from a database or API)
byte[] pdfBytes1 = File.ReadAllBytes("document1.pdf");
byte[] pdfBytes2 = File.ReadAllBytes("document2.pdf");

// Create PdfDocument objects from byte arrays
var pdf1 = new PdfDocument(pdfBytes1);
var pdf2 = new PdfDocument(pdfBytes2);

// Merge the two PDF documents
PdfDocument combinedPdf = PdfDocument.Merge(pdf1, pdf2);

// Convert the combined PDF back to byte array
byte[] mergedPdfBytes = combinedPdf.BinaryData;

// Save the merged PDF (optional)
File.WriteAllBytes("merged.pdf", mergedPdfBytes);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

輸出

如何在 C# 中合併兩個 PDF 位元組陣列:圖 2 - 合併的 PDF 文件

上面的程式碼演示了核心合併功能。 首先,我們從我們的位元組陣列創建 PdfDocument 對象。 IronPDF 自动解析二進制數據並創建正確的 PDF 文件對象。

PdfDocument.Merge() 方法將多個 PDF 文件合併為一個,保留所有頁面、格式和所有來源文件的內容。 最後,我們可以使用 BinaryData 屬性將合併的文檔作為位元組陣列訪問,非常適合儲存到數據庫或通過 API 發送。 將位元組轉換成新的 PDF 的過程由庫處理,為我們提供了一個新的文件。

有哪些替代方法可用於合併 PDF?

IronPDF 提供了靈活的選項來合併 PDF 文件。 當您需要合併多於兩個的 PDF 文件時,您可以使用 List 重載。 以下演示了這一方法:

// Define pdfByteArrays as a list of byte arrays
List<byte[]> pdfByteArrays = new List<byte[]>
{
    // Add sample byte arrays representing PDFs
    File.ReadAllBytes("example1.pdf"),
    File.ReadAllBytes("example2.pdf")
};

List<PdfDocument> pdfsToMerge = new List<PdfDocument>();
foreach (var byteArray in pdfByteArrays)
{
    pdfsToMerge.Add(new PdfDocument(byteArray));
}

PdfDocument combinedPdf = PdfDocument.Merge(pdfsToMerge);
byte[] finalPdfBytes = combinedPdf.BinaryData;
// Define pdfByteArrays as a list of byte arrays
List<byte[]> pdfByteArrays = new List<byte[]>
{
    // Add sample byte arrays representing PDFs
    File.ReadAllBytes("example1.pdf"),
    File.ReadAllBytes("example2.pdf")
};

List<PdfDocument> pdfsToMerge = new List<PdfDocument>();
foreach (var byteArray in pdfByteArrays)
{
    pdfsToMerge.Add(new PdfDocument(byteArray));
}

PdfDocument combinedPdf = PdfDocument.Merge(pdfsToMerge);
byte[] finalPdfBytes = combinedPdf.BinaryData;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此方法允許您高效地合併任何數量的 PDF 文件。 每個 PDF 都是從其位元組陣列載入到 PdfDocument 對象中,加入到一個列表中,然後在單個操作中合併。

使用 MemoryStream 提高靈活性

您也可以使用 MemoryStream 來提高處理流時的控制。 以下程式碼演示了這一做法:

using (var stream1 = new MemoryStream(pdfBytes1))
using (var stream2 = new MemoryStream(pdfBytes2))
{
    var pdf1 = new PdfDocument(stream1);
    var pdf2 = new PdfDocument(stream2);
    var merged = PdfDocument.Merge(pdf1, pdf2);
    byte[] result = merged.BinaryData;
}
using (var stream1 = new MemoryStream(pdfBytes1))
using (var stream2 = new MemoryStream(pdfBytes2))
{
    var pdf1 = new PdfDocument(stream1);
    var pdf2 = new PdfDocument(stream2);
    var merged = PdfDocument.Merge(pdf1, pdf2);
    byte[] result = merged.BinaryData;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

使用流提供了更好的記憶體管理,以處理較大的 PDF 文件,並在與其他使用流式 I/O 的系統集成時提高靈活性。 這個示例是一種有效使用流的絕佳方式。 需要時可以檢查流上的 Length 屬性。

如何處理常見的 PDF 文件合併情境?

在一般情況下,您從數據庫獲取 PDF,並需要合併它們:

public string MergePdfDocumentsFromDatabase(List<int> documentIds)
{
    List<PdfDocument> documents = new List<PdfDocument>();

    foreach (int id in documentIds)
    {
        // Fetch PDF byte array from database
        byte[] pdfData = GetPdfFromDatabase(id); // Assume this function exists
        documents.Add(new PdfDocument(pdfData));
    }

    // Merge all documents
    PdfDocument mergedDocument = PdfDocument.Merge(documents);

    // The document is saved back to a stream or to the server
    byte[] resultBytes = mergedDocument.BinaryData;

    // For this example, we return a success string
    return "Merge True: Document successfully combined and saved.";
}

public PdfDocument AddPageToPdf(PdfDocument existingDoc, byte[] newPageBytes)
{
    // Create a PdfDocument object from the new page bytes
    using var stream = new MemoryStream(newPageBytes);
    var newPageDoc = new PdfDocument(stream);

    // Get the first page of the new document
    var newPage = newPageDoc.Pages[0];

    // Add the page to the existing document
    existingDoc.Pages.Add(newPage);

    // Return the modified document
    return existingDoc;
}
public string MergePdfDocumentsFromDatabase(List<int> documentIds)
{
    List<PdfDocument> documents = new List<PdfDocument>();

    foreach (int id in documentIds)
    {
        // Fetch PDF byte array from database
        byte[] pdfData = GetPdfFromDatabase(id); // Assume this function exists
        documents.Add(new PdfDocument(pdfData));
    }

    // Merge all documents
    PdfDocument mergedDocument = PdfDocument.Merge(documents);

    // The document is saved back to a stream or to the server
    byte[] resultBytes = mergedDocument.BinaryData;

    // For this example, we return a success string
    return "Merge True: Document successfully combined and saved.";
}

public PdfDocument AddPageToPdf(PdfDocument existingDoc, byte[] newPageBytes)
{
    // Create a PdfDocument object from the new page bytes
    using var stream = new MemoryStream(newPageBytes);
    var newPageDoc = new PdfDocument(stream);

    // Get the first page of the new document
    var newPage = newPageDoc.Pages[0];

    // Add the page to the existing document
    existingDoc.Pages.Add(newPage);

    // Return the modified document
    return existingDoc;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此模式非常適合於需要合併發票、報告或任何儲存在數據庫中的其他 PDF 文件的情境。 合併的文件保持了所有來源 PDF 的原始質量和格式。 這些對象完全在記憶體中處理。 如果需要,您還可以編輯頁面。

處理錯誤和常見錯誤

在實施此程式碼時,重要的是要處理潛在的錯誤情況。 例如,如果文件不可讀(錯誤的路徑)或位元組陣列不代表有效的 PDF,則 new PdfDocument() 對象的創建可能會拋出異常。 始終使用try-catch塊。 如果您不熟悉系統,容易發生錯誤。 在處理之前,始終驗證陣列的長度。

示例: 在嘗試讀取位元組之前,始終檢查文件路徑是否存在。 如果位元組陣列是 null,則開啟操作會失敗。

創建、刪除或匯入這些文件的能力通常由具有適當密碼或站點安全的用戶管理。這可確保對文件的安全訪問,並防止未經授權的寫入或儲存操作。 此話題在 IronPDF 網站上的附加話題中有探討。

結論

使用 IronPDF 合併 PDF 位元組陣列消除了 C# 中傳統上與 PDF 操作相關的複雜性。 無論您是處理來自數據庫的文檔、API 響應或內存中的處理,IronPDF 的直觀 API 使合併 PDF 僅需調用一個方法即可完成。 我們希望這種方法能夠幫助您實現目標。 最終結果是一個乾淨的合併 PDF 文件。 感謝您的閱讀,如果您有進一步的問題,請隨時回覆。

Get started with a free trial to experience how IronPDF can streamline your PDF processing workflows, or 探索我們的許可選項以用於實際應用。

NuGet 用 NuGet 安裝

PM >  Install-Package IronPdf

NuGet 查看 https://www.nuget.org/packages/IronPdf 以快速安裝。超過 1000 萬次下載,它正在用 C# 改變 PDF 開發。 您還可以下載 DLLWindows 安裝程序

常見問題解答

如何在 C# 中合併兩個 PDF 位元組數組?

您可以使用 IronPDF 在 C# 中合併兩個 PDF 位元組數組。它允許您輕鬆地將多個以位元組數組形式儲存的 PDF 文件合併到一個 PDF 文件中,而無需將它們保存到磁碟。

使用 IronPDF 合併 PDF 位元組數組有哪些好處?

IronPDF 透過提供直覺的 API 簡化了 PDF 位元組數組的合併過程。它能夠有效率地在記憶體中處理 PDF 文件,這對於從資料庫或 Web 服務檢索 PDF 文件的應用程式來說非常理想。

IronPDF能否在不儲存到磁碟的情況下合併PDF檔案?

是的,IronPDF 可以合併 PDF 檔案而無需將其儲存到磁碟。它直接從位元組數組處理 PDF 文件,因此非常適合基於記憶體的操作。

是否可以使用 IronPDF 合併從 Web 服務接收的 PDF 檔案?

當然可以。 IronPDF 可以合併從 Web 服務接收的以位元組數組形式存在的 PDF 文件,從而實現與遠端 PDF 來源的無縫整合。

在 C# 中合併 PDF 位元組數組的常見應用是什麼?

一個常見的應用場景是將從資料庫中檢索到的多個 PDF 文件合併到一個 PDF 文件中,然後再在 C# 應用程式中進行處理或顯示。

IronPDF是否支援在記憶體中處理PDF檔案?

是的,IronPDF 支援在記憶體中處理 PDF 文件,這對於需要快速處理 PDF 文件而無需中間磁碟儲存的應用程式至關重要。

IronPDF如何處理從資料庫合併PDF文件的問題?

IronPDF 可讓您直接處理 PDF 位元組數組,從而處理來自資料庫的 PDF 合併,無需臨時文件儲存。

IronPDF能否將多個PDF文件合併成一個文件?

是的,IronPDF 可以透過合併位元組數組將多個 PDF 文件合併為一個文件,從而為創建複合 PDF 文件提供了簡化的方法。

Curtis Chau
技術作家

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

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