如何在C#中將條碼作為PDF創建

如何在 C# 中將 BarCode 匯出為 PDF 格式;

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronBarcode 可讓 C# 開發人員透過三種方法將條碼匯出為 PDF 檔案:直接儲存至檔案、轉換為二進位資料或串流至記憶體 - 所有這些都只需簡單的單行操作即可完成。

快速入門:立即將條碼匯出為 PDF

本範例展示了在 .NET 中使用 IronBarcode 將條碼匯出為 PDF 是多麼簡單。 只需一行即可產生 PDF 格式的條碼——非常適合快速儲存、串流或傳送。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronBarcode

    PM > Install-Package BarCode

  2. 複製並運行這段程式碼。

    var pdfBytes = IronBarCode.BarcodeWriter.CreateBarcode("FastPDF", IronBarCode.BarcodeWriterEncoding.Code128).ToPdfBinaryData();
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronBarcode,免費試用!
    arrow pointer

如何將 BarCode 匯出為 PDF 檔案?

為何直接將 BarCode 儲存至 PDF 檔案?

當您需要產生實體文件、建立可列印的標籤,或將條碼歸檔以長期儲存時,直接將條碼儲存為 PDF 檔案是最直接的方法。 此方法特別適用於庫存管理系統、出貨標籤和文件生成工作流程,其中 PDF 格式可確保在不同平台和印表機上呈現一致。

若要將條碼儲存為 PDF 檔案,請先使用 BarcodeWriter.CreateBarcode 建立 GeneratedBarcode 物件,然後再使用 SaveAsPdf() 方法轉換並儲存至磁碟。 以下程式碼片段演示了其工作原理。

:path=/static-assets/barcode/content-code-examples/how-to/ExportBarcodeAsPdfFile.cs
using IronBarCode;

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.DataMatrix);
myBarcode.SaveAsPdf("myBarcode.pdf");
Imports IronBarCode

Private myBarcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.DataMatrix)
myBarcode.SaveAsPdf("myBarcode.pdf")
$vbLabelText   $csharpLabel

如需更多進階的條碼建立選項,請參閱我們關於 從各種資料來源建立條碼的全面指南。

有哪些檔案路徑選項可用?

IronBarcode 提供儲存 PDF 檔案的彈性檔案路徑選項。 您可以指定絕對路徑、相對路徑或使用環境變數。 以下是一個更詳細的範例,顯示不同的路徑選項:

using IronBarCode;
using System;
using System.IO;

// Create a barcode
GeneratedBarcode barcode = BarcodeWriter.CreateBarcode("PRODUCT-12345", BarcodeEncoding.Code128);

// Save to current directory
barcode.SaveAsPdf("barcode.pdf");

// Save to absolute path
barcode.SaveAsPdf(@"C:\BarcodeExports\product_barcode.pdf");

// Save to relative path
barcode.SaveAsPdf(@"..\..\exports\barcode.pdf");

// Save using environment path
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
barcode.SaveAsPdf(Path.Combine(documentsPath, "barcode.pdf"));
using IronBarCode;
using System;
using System.IO;

// Create a barcode
GeneratedBarcode barcode = BarcodeWriter.CreateBarcode("PRODUCT-12345", BarcodeEncoding.Code128);

// Save to current directory
barcode.SaveAsPdf("barcode.pdf");

// Save to absolute path
barcode.SaveAsPdf(@"C:\BarcodeExports\product_barcode.pdf");

// Save to relative path
barcode.SaveAsPdf(@"..\..\exports\barcode.pdf");

// Save using environment path
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
barcode.SaveAsPdf(Path.Combine(documentsPath, "barcode.pdf"));
Imports IronBarCode
Imports System
Imports System.IO

' Create a barcode
Dim barcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("PRODUCT-12345", BarcodeEncoding.Code128)

' Save to current directory
barcode.SaveAsPdf("barcode.pdf")

' Save to absolute path
barcode.SaveAsPdf("C:\BarcodeExports\product_barcode.pdf")

' Save to relative path
barcode.SaveAsPdf("..\..\exports\barcode.pdf")

' Save using environment path
Dim documentsPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
barcode.SaveAsPdf(Path.Combine(documentsPath, "barcode.pdf"))
$vbLabelText   $csharpLabel

本文將探討如何使用 IronBarcode 將條碼匯出至 PDF。 使用 IronBarcode,條碼可以匯出為檔案、二進位資料或記憶體流。 如需 IronBarcode 功能的完整概述,請訪問我們的 入門文件

何時應該使用檔案匯出 vs 其他方法?

選擇檔案匯出時:

  • 您需要永久儲存 BarCode
  • 產生報告或可列印文件
  • 建立離線處理的批次檔案
  • 與檔案型系統整合

考慮二進位資料或串流時:

  • 處理需要立即回應的網路應用程式
  • 在資料庫中儲存
  • 在沒有檔案系統存取的情況下透過 API 傳送
  • 在記憶體受限的環境中進行處理

如何將 BarCode 匯出為 PDF 二進位資料?

為何使用二進位資料而非檔案?

二進位資料匯出非常適合需要在記憶體中操作 PDF 資料而不需建立臨時檔案的情況。 這種方法在網路應用程式、雲端環境以及使用資料庫時特別有價值。 它消除了檔案 I/O 作業,藉由將資料保留在記憶體中來改善效能與安全性。

若要匯出為 PDF 二進位數據,請產生條碼,然後呼叫ToPdfBinaryData()方法。 這會將 PDF 二進位資料輸出為byte[]陣列。 以下程式碼片段演示了其工作原理。

:path=/static-assets/barcode/content-code-examples/how-to/ExportBarcodeAsPdfBinaryData.cs
using IronBarCode;

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.DataMatrix);
byte[] myBarcodeByte = myBarcode.ToPdfBinaryData();
Imports IronBarCode

Private myBarcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.DataMatrix)
Private myBarcodeByte() As Byte = myBarcode.ToPdfBinaryData()
$vbLabelText   $csharpLabel

您也可以在匯出前自訂 BarCode 的外觀。 進一步了解 自訂 BarCode 樣式 以強化您的 PDF 匯出。

如何將二進位 PDF 資料傳送至 API?

二進位 PDF 資料可輕鬆透過 REST API 傳輸,因此非常適合微服務架構。 以下是透過 HTTP 請求傳送 BarCode PDF 資料的實例:

using IronBarCode;
using System.Net.Http;
using System.Threading.Tasks;

public async Task SendBarcodeToAPI()
{
    // Generate barcode and get binary data
    GeneratedBarcode barcode = BarcodeWriter.CreateBarcode("API-DATA-123", BarcodeEncoding.QRCode);
    byte[] pdfData = barcode.ToPdfBinaryData();

    // Send via HTTP POST
    using (HttpClient client = new HttpClient())
    {
        ByteArrayContent content = new ByteArrayContent(pdfData);
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");

        HttpResponseMessage response = await client.PostAsync("https://api.example.com/barcode", content);
        // Handle response
    }
}
using IronBarCode;
using System.Net.Http;
using System.Threading.Tasks;

public async Task SendBarcodeToAPI()
{
    // Generate barcode and get binary data
    GeneratedBarcode barcode = BarcodeWriter.CreateBarcode("API-DATA-123", BarcodeEncoding.QRCode);
    byte[] pdfData = barcode.ToPdfBinaryData();

    // Send via HTTP POST
    using (HttpClient client = new HttpClient())
    {
        ByteArrayContent content = new ByteArrayContent(pdfData);
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");

        HttpResponseMessage response = await client.PostAsync("https://api.example.com/barcode", content);
        // Handle response
    }
}
Imports IronBarCode
Imports System.Net.Http
Imports System.Threading.Tasks

Public Async Function SendBarcodeToAPI() As Task
    ' Generate barcode and get binary data
    Dim barcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("API-DATA-123", BarcodeEncoding.QRCode)
    Dim pdfData As Byte() = barcode.ToPdfBinaryData()

    ' Send via HTTP POST
    Using client As New HttpClient()
        Dim content As New ByteArrayContent(pdfData)
        content.Headers.ContentType = New System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf")

        Dim response As HttpResponseMessage = Await client.PostAsync("https://api.example.com/barcode", content)
        ' Handle response
    End Using
End Function
$vbLabelText   $csharpLabel

二進位匯出的常見使用案例有哪些?

二進位匯出常用於:

  • 資料庫儲存:將 PDF 條碼儲存為資料庫中的 BLOB 資料
  • 電子郵件附件:將 BarCode 附加到電子郵件,而無需建立臨時檔案
  • 雲端儲存:直接上傳至 Azure Blob Storage 或 AWS S3 等服務
  • 記憶體內處理:無需磁碟 I/O 即可鏈結多重作業
  • Web API 回應:在 HTTP 回應中直接傳回 PDF 資料

如需其他條碼產生技術和最佳實務,請造訪我們的 從各種來源建立條碼指南。 您也可以瞭解 在現有 PDF 上標示 BarCode 的相關資訊,以應用更進階的 PDF 操作情境。

如何將 BarCode 匯出為 PDF 串流?

Why Use Streams for PDF Export?

Streams 提供了處理 PDF 資料最靈活的方法,尤其是在與其他 .NET 函式庫整合或需要對資料流進行細緻控制時。 在記憶體效率極為重要的大規模作業中,Streams 尤其有用,因為它們允許緩衝讀取和寫入。

若要匯出為記憶體流,請產生條碼,然後呼叫ToPdfStream()方法。 此方法傳回一個System.IO.Stream物件。 以下程式碼片段演示了其工作原理。

:path=/static-assets/barcode/content-code-examples/how-to/ExportBarcodeAsPdfStream.cs
using IronBarCode;
using System.IO;

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.DataMatrix);
Stream myBarcodeStream = myBarcode.ToPdfStream();
Imports IronBarCode
Imports System.IO

Private myBarcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.DataMatrix)
Private myBarcodeStream As Stream = myBarcode.ToPdfStream()
$vbLabelText   $csharpLabel

如需進階的串流操作和其他匯出格式,請參閱我們關於 將 BarCode 匯出為串流的詳細指南。

如何正確處理記憶體串流?

正確的串流處理對於防止記憶體洩漏和確保資源的有效使用至關重要。 以下是一個展示最佳實務的綜合範例:

using IronBarCode;
using System.IO;

public void ProcessBarcodeStream()
{
    // Always use using statements for proper disposal
    using (Stream pdfStream = BarcodeWriter.CreateBarcode("STREAM-123", BarcodeEncoding.Code39).ToPdfStream())
    {
        // Example 1: Copy to file
        using (FileStream fileStream = File.Create("output.pdf"))
        {
            pdfStream.CopyTo(fileStream);
        }

        // Reset stream position for reuse
        pdfStream.Position = 0;

        // Example 2: Read into buffer
        byte[] buffer = new byte[pdfStream.Length];
        pdfStream.Read(buffer, 0, buffer.Length);

        // Example 3: Process with another library
        // ProcessPdfStream(pdfStream);
    }
}
using IronBarCode;
using System.IO;

public void ProcessBarcodeStream()
{
    // Always use using statements for proper disposal
    using (Stream pdfStream = BarcodeWriter.CreateBarcode("STREAM-123", BarcodeEncoding.Code39).ToPdfStream())
    {
        // Example 1: Copy to file
        using (FileStream fileStream = File.Create("output.pdf"))
        {
            pdfStream.CopyTo(fileStream);
        }

        // Reset stream position for reuse
        pdfStream.Position = 0;

        // Example 2: Read into buffer
        byte[] buffer = new byte[pdfStream.Length];
        pdfStream.Read(buffer, 0, buffer.Length);

        // Example 3: Process with another library
        // ProcessPdfStream(pdfStream);
    }
}
Imports IronBarCode
Imports System.IO

Public Sub ProcessBarcodeStream()
    ' Always use using statements for proper disposal
    Using pdfStream As Stream = BarcodeWriter.CreateBarcode("STREAM-123", BarcodeEncoding.Code39).ToPdfStream()
        ' Example 1: Copy to file
        Using fileStream As FileStream = File.Create("output.pdf")
            pdfStream.CopyTo(fileStream)
        End Using

        ' Reset stream position for reuse
        pdfStream.Position = 0

        ' Example 2: Read into buffer
        Dim buffer As Byte() = New Byte(pdfStream.Length - 1) {}
        pdfStream.Read(buffer, 0, buffer.Length)

        ' Example 3: Process with another library
        ' ProcessPdfStream(pdfStream)
    End Using
End Sub
$vbLabelText   $csharpLabel

何時應該選擇串流而非二進位資料?

選擇流時:

  • 與其他期待串流輸入的函式庫整合
  • 處理大型檔案,將整個內容載入記憶體是不可行的
  • 在 Web 應用程式中實作串流回應
  • 與其他基於串流的 API 進行連鎖操作
  • 需要緩衝讀取/寫入以優化效能

選擇二進位資料時:

  • 需要在變數或資料庫中進行簡單的儲存
  • 快速序列化,無需複雜處理 -使用需要位元組數組的 API

如需其他條碼生成技術和最佳實踐,請訪問我們全面的 BarCode 教程。 您也可以瞭解 在現有 PDF 上標示 BarCode 的相關資訊,以應用更進階的 PDF 操作情境。

常見問題解答

如何在 C# 中將 BarCode 匯出至 PDF?

IronBarcode 提供三種方法將條碼匯出成 PDF 檔案:使用 SaveAsPdf() 直接儲存至檔案、使用 ToPdfBinaryData() 轉換成二元資料,或串流至記憶體。最簡單的方法是使用 BarcodeWriter.CreateBarcode(),然後再使用您偏好的匯出方法。

只需一行代碼就能生成 PDF BarCode 嗎?

是的,IronBarcode 可以單行生成 PDF 條碼。只需使用: var pdfBytes = IronBarCode.BarcodeWriter.CreateBarcode("FastPDF", IronBarCode.BarcodeWriterEncoding.Code128).ToPdfBinaryData(); 即可立即創建一個PDF-ready條碼。

將 BarCode 儲存為 PDF 檔案時,有哪些檔案路徑選項?

IronBarcode 支援彈性的檔案路徑選項,包括絕對路徑、相對路徑和環境變數。您可以使用SaveAsPdf()使用 "barcode.pdf 「這樣的路徑表示當前目錄,」C:\BarcodeExports\product_barcode.pdf "表示絕對路徑,或者使用Path.Combine()與Environment.SpecialFolder表示系統路徑。

何時應該直接將 BarCode 儲存為 PDF 檔案,而非使用串流?

使用 IronBarcode 的 SaveAsPdf() 方法直接保存為 PDF 檔案是生成實體文件、創建可列印標籤或存檔條碼以長期儲存的理想選擇。這種方法對於庫存管理系統、出貨標籤以及需要一致 PDF 渲染的文件工作流程特別有用。

如何將 BarCode 資料轉換為 PDF 二進位資料?

使用 IronBarcode 的 ToPdfBinaryData() 方法將條碼轉換為二進位資料。首先使用 BarcodeWriter.CreateBarcode() 建立一個 GeneratedBarcode 物件,然後呼叫 ToPdfBinaryData() 來取得 PDF 成為適合資料庫儲存或網路傳輸的位元組陣列。

我可以直接將 BarCode 串流至記憶體,而不是儲存至磁碟嗎?

是的,IronBarcode 支援將條碼串流至記憶體,讓您無需建立實體檔案即可處理 PDF 資料。這對於需要動態提供 PDF 條碼而無需磁碟 I/O 操作的 Web 應用程式或 API 來說是完美的。

Hairil Hasyimi Bin Omar
軟體工程師
就像所有優秀的工程師一樣,Hairil 也是一位狂熱的學習者。他不斷精進 C#、Python 和 Java 的知識,利用這些知識為整個 Iron Software 的團隊成員增加價值。Hairil 從馬來西亞的 Universiti Teknologi MARA 大學加入 Iron Software 團隊,畢業於該校的化學與流程工程學系,並取得學士學位。
準備好開始了嗎?
Nuget 下載 2,070,733 | 版本: 2026.2 剛剛發布