跳過到頁腳內容
使用IRONPDF

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

處理以位元組數組形式儲存的PDF文件

在現代 C# 應用程式中,處理以位元組數組形式儲存的 PDF 檔案是一個常見的需求。 無論您是從資料庫中檢索 PDF 文檔、從 Web 服務接收 PDF 文檔,還是在內存中處理 PDF 文檔,將多個 PDF 文件合併為一個 PDF 文件而不保存到磁碟的功能都至關重要。

IronPDF憑藉其直覺的API,使這一過程變得異常簡單。 您可以輕鬆地將兩個或多個 PDF 文件合併,從而實現創建合併 PDF 文件(即單一 PDF 輸出)的要求。 在本文中,我們將探討如何在 C# 中合併 PDF 位元組數組,以及完成此任務的不同方法。

什麼是 PDF 位元組數組?為什麼要合併它們?

位元組數組本質上是記憶體中表示 PDF 檔案的原始二進位資料。 在 C# 中處理 PDF 文件時,您經常會遇到 PDF 文件以位元組數組形式存在,而不是以實體文件形式存在於磁碟上的情況。 當從資料庫中檢索以二進位資料形式儲存的 PDF 文檔,或透過伺服器從 REST API 接收 PDF 文檔時,這種情況尤其常見。

簡單地將兩個 PDF 位元組陣列連接起來是行不通的——與文字檔案不同,PDF 檔案具有複雜的內部結構,包含標題、交叉引用表和特定格式。 如果你直接嘗試連接這些字節,肯定會出錯。 你需要一個合適的 PDF 庫來解析這些位元組數組並正確地將它們組合起來。 IronPDF 可以處理所有這些複雜性,只需幾行程式碼即可合併 PDF 文件。 這是該庫幫助你理解和解決的核心問題。 隨便瀏覽一下論壇,你都會看到有人討論這個問題。

如何設定 IronPDF 以進行 PDF 合併?

IronPDF 的入門非常簡單。 首先,在您的專案中安裝 IronPDF NuGet 套件:

Install-Package IronPdf
Install-Package IronPdf
SHELL

安裝完成後,將以下命名空間新增至您的 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# 中使用 IronPDF 合併兩個 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# 中使用 IronPDF 合併兩個 PDF 位元組數組:圖 2 - 合併後的 PDF 文件

上面的程式碼示範了核心合併功能。 首先,我們從位元組數組建立PdfDocument物件。 IronPDF 會自動處理二進位資料的解析並建立正確的 PDF 文件物件。

PdfDocument.Merge()方法將多個 PDF 文件合併為一個 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>();
for (int i = 0; i < pdfByteArrays.Count; i++)
{
    pdfsToMerge.Add(new PdfDocument(pdfByteArrays[i]));
}
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>();
for (int i = 0; i < pdfByteArrays.Count; i++)
{
    pdfsToMerge.Add(new PdfDocument(pdfByteArrays[i]));
}
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 檔案並需要將它們合併時:

// A String to represent the object being processed
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.";
}
// Another method to show how to process a single page
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;
}
// A String to represent the object being processed
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.";
}
// Another method to show how to process a single page
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,則建立新的PdfDocument()物件可能會引發異常。 務必使用 try-catch 程式碼區塊。 論壇上關於此主題的貼文對錯誤處理進行了詳盡的討論。 如果你不熟悉這個系統,很容易犯錯。 處理數組之前務必先檢查數組的長度。

例如:在嘗試讀取位元組之前,務必檢查檔案路徑是否存在。 如果位元組數組為空,則開啟操作將失敗。

建立、刪除或匯入這些文件的功能通常由擁有相應密碼或網站安全設定的使用者管理。這確保了對文件的安全訪問,並防止未經授權的寫入或保存操作。 IronPDF網站的新主題中涵蓋了這個主題。

結論

將 PDF 位元組陣列與 IronPDF 合併,消除了傳統上與 C# 中 PDF 操作相關的複雜性。 無論您是處理來自資料庫的文件、API 回應還是記憶體處理,IronPDF 簡單易用的 API 都能讓合併 PDF 像呼叫單一方法一樣簡單。 你找到了一個解決這個問題的好方法! 我們希望這種方法能幫助您實現目標。 我們之前發布過類似的主題,這篇文章是掌握 PDF 操作的入門指南。 最終結果是一個乾淨、合併後的PDF文件。 感謝閱讀,如有任何疑問,請回覆。

立即開始免費試用,體驗 IronPDF 如何簡化您的 PDF 處理工作流程,或了解我們適用於生產環境的授權選項

!{--010011000100100101000010010100100100000101010010010110010101111101001110010101010101010101010101010101010101010 0100010111110100100101001101010100010000010100110001001100010111110100001001001100010011110010101010

常見問題解答

如何使用 C# 合併兩個 PDF 位元組陣列?

您可以使用 IronPDF 在 C# 中合併兩個 PDF 位元組數組。該庫允許您輕鬆地合併以位元組數組、內存流甚至資料庫形式存儲的多個 PDF 文件,並提供了簡潔明了的程式碼範例。

使用 IronPDF 合併 PDF 位元組數組有什麼優勢?

IronPDF 透過提供直覺的功能來處理 PDF 操作的複雜性,從而簡化了合併 PDF 位元組陣列的過程,確保高效可靠的結果。

IronPDF 能否處理來自不同資料來源的 PDF 合併?

是的,IronPDF 可以合併來自各種資料來源的 PDF 文件,包括位元組數組、記憶體流和資料庫,使其成為功能強大的 PDF 文件操作工具。

是否可以使用 IronPDF 將儲存在記憶體流中的 PDF 檔案合併?

當然,IronPDF 支援合併儲存在記憶體流中的 PDF 文件,從而可以直接在您的 C# 應用程式中實現無縫整合和合併功能。

IronPDF 是否需要任何額外的軟體來合併 PDF 位元組數組?

不,IronPDF 是一個獨立的庫,無需額外的軟體即可合併 PDF 位元組數組。它的設計旨在輕鬆整合到您的 C# 專案中。

IronPDF 如何保證合併後 PDF 的品質?

IronPDF 在合併過程中保持 PDF 的原始品質和格式,確保最終文件品質高,並保留所有原始內容。

IronPDF 合併 PDF 位元組數組後可以輸出哪些文件格式?

合併後,IronPDF 可以以標準 PDF 格式輸出最終文檔,確保與任何 PDF 檢視器或編輯器相容。

IronPDF 能否合併加密的 PDF 位元組數組?

是的,IronPDF 可以處理加密的 PDF 位元組數組,前提是您擁有必要的權限,並在合併過程中傳遞正確的解密憑證。

使用 IronPDF 合併 PDF 位元組數組需要哪些程式設計知識?

只需具備 C# 的基本知識即可使用 IronPDF 合併 PDF 位元組數組,因為該庫提供了簡單易懂的方法和全面的文檔來引導您完成整個過程。

是否有針對IronPDF故障排查的支援服務?

是的,IronPDF 提供全面的文件和支持,以協助解決在使用該程式庫進行 PDF 處理任務時可能出現的任何問題。

Curtis Chau
技術作家

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

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