如何使用 IronBarcode 在 PDF 文檔中創建並印章條碼

如何使用 C# 在 PDF 上新增條碼

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

使用 IronBarcode 的 CreateBarcode 方法,在 C# 中將條碼新增至現有的 PDF 文件中,對於單頁使用 StampToExistingPdfPage,對於多頁使用 StampToExistingPdfPages,並指定座標和頁碼。

快速入門:將產生的條碼新增至 PDF 頁面

本範例示範如何使用 IronBarCode 的 CreateBarcode 產生條碼,並將其印製到現有的 PDF 頁面上。 請提供PDF檔案的路徑、位置座標和頁碼。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/BarCode

    PM > Install-Package BarCode
  2. 複製並運行這段程式碼。

    IronBarCode.BarcodeWriter.CreateBarcode("https://my.site", IronBarCode.BarcodeEncoding.QRCode, 150, 150)
        .StampToExistingPdfPage("report.pdf", x: 50, y: 50, pageNumber: 1);
  3. 部署到您的生產環境進行測試

    今天就在您的專案中開始使用免費試用IronBarcode

    arrow pointer

如何在現有的PDF頁面上新增條碼?

Apart from exporting barcodes as PDF, IronBarcode enables stamping the GeneratedBarcode directly onto existing PDF documents. 在向現有報告、發票或表單中新增追蹤代碼、庫存標籤或文件識別碼時,此功能非常有用。 以下程式碼片段演示了這項任務。

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

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.Code128, 200, 100);
myBarcode.StampToExistingPdfPage("pdf_file_path.pdf", x: 200, y: 100, 3, "password");
$vbLabelText   $csharpLabel

StampToExistingPdfPage 需要哪些參數?

程式碼片段使用 StampToExistingPdfPage() 物件呼叫 GeneratedBarcode 方法,將該物件印章到 PDF 文件上。 這種方法既靈活又簡單。 以下是此方法的參數:

  • pdfFilePath: 表示 PDF 文件路徑(相對或絕對)的 System.String
  • x: 表示從左邊緣開始的水平位置(以像素為單位)的 System.Int32
  • y: 一個System.Int32 類型的值,表示從底部邊緣開始的垂直位置(以像素為單位)。
  • pageNumber: 一個System.Int32表示頁碼(從 1 開始索引,第一頁為 1)。
  • password: 用於受密碼保護的 PDF 的System.String (可選)。

何時應該使用 StampToExistingPdfPage?

執行此程式碼片段會將 GeneratedBarcode 直接加入 PDF 文件中,而無需中間儲存。 此方法適用於以下情況:

  • 貨運標籤或送貨單上的唯一追蹤碼 生產報告上的批號
  • 法律或監管表格上的文件控制編號
  • 用於數位認證或快速存取連結的二維碼

直接蓋章方式節省了處理時間,且無需臨時文件。 For information on different barcode types, see the supported barcode formats guide.

如何在多個PDF頁面上新增條碼?

有時同一個條碼需要印在多張紙上。 常見用途包括:在多頁報告的每一頁上套用文件標識符,在技術文件中新增版本控製代碼,或在機密資料的每一頁上插入安全條碼。 不要循環使用單頁方法,而是使用 StampToExistingPdfPages() 類別中的方法。 以下程式碼片段示範了這種方法。

:path=/static-assets/barcode/content-code-examples/how-to/StampBarcodeOnMultiplePdfPages.cs
using IronBarCode;
using System.Collections.Generic;

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.Code128, 200, 100);
List<int> pages = new List<int>();
pages.Add(1);
pages.Add(2);
pages.Add(3);
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x: 200, y: 100, pages, "password");
$vbLabelText   $csharpLabel

為了提高靈活性,可以使用 LINQ 動態產生頁面範圍:

// Stamp on all even pages from 2 to 10
var evenPages = Enumerable.Range(1, 10).Where(x => x % 2 == 0).ToList();
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x: 200, y: 100, evenPages, "password");

// Stamp on the first and last 3 pages of a 20-page document
var selectedPages = new List<int> { 1, 2, 3, 18, 19, 20 };
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x: 200, y: 100, selectedPages, "password");
// Stamp on all even pages from 2 to 10
var evenPages = Enumerable.Range(1, 10).Where(x => x % 2 == 0).ToList();
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x: 200, y: 100, evenPages, "password");

// Stamp on the first and last 3 pages of a 20-page document
var selectedPages = new List<int> { 1, 2, 3, 18, 19, 20 };
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x: 200, y: 100, selectedPages, "password");
$vbLabelText   $csharpLabel

StampToExistingPdfPages 接受哪些參數?

以下是此方法的參數:

  • pdfFilePath: 表示 PDF 文件路徑的System.String
  • x: 以像素為單位的水平位置的System.Int32
  • y: 一個System.Int32 類型的值,表示以像素為單位的垂直位置。
  • pageNumbers: 一個IEnumerable待蓋章的頁數(1-索引)。
  • password: 用於受密碼保護的 PDF 的System.String (可選)。

為什麼要使用 StampToExistingPdfPages 而不是循環?

此方法無需手動迭代即可在多頁上有效地蓋印條碼,從而提高條碼的可讀性和效能。 內部實作優化了PDF處理,結果如下:

-執行速度更快:PDF 文件只需打開和處理一次,無需多次處理 -更低的記憶體佔用:高效率管理大型 PDF 檔案的資源 -更簡潔的程式碼:無需手動循環和錯誤處理管理 -原子操作:所有頁面在一次操作中被蓋章

高級沖壓技術

蓋章前自訂條碼外觀

在將條碼新增至 PDF 之前,請先自訂其外觀。 IronBarcode offers extensive customization options:

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("INVOICE-2024-001", BarcodeEncoding.Code128, 250, 80);

// Customize the appearance
myBarcode.AddAnnotationTextAboveBarcode("Invoice Number");
myBarcode.AddAnnotationTextBelowBarcode("Scan for digital copy");
myBarcode.SetMargins(10);
myBarcode.ChangeBarcodeForegroundColor(System.Drawing.Color.DarkBlue);

// Now stamp the customized barcode
myBarcode.StampToExistingPdfPage("invoice.pdf", x: 450, y: 700, pageNumber: 1);
GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("INVOICE-2024-001", BarcodeEncoding.Code128, 250, 80);

// Customize the appearance
myBarcode.AddAnnotationTextAboveBarcode("Invoice Number");
myBarcode.AddAnnotationTextBelowBarcode("Scan for digital copy");
myBarcode.SetMargins(10);
myBarcode.ChangeBarcodeForegroundColor(System.Drawing.Color.DarkBlue);

// Now stamp the customized barcode
myBarcode.StampToExistingPdfPage("invoice.pdf", x: 450, y: 700, pageNumber: 1);
$vbLabelText   $csharpLabel

使用不同類型的條碼

不同的應用場景需要不同的條碼類型。二維碼適用於網址和大型資料集,而Code128條碼則適用於字母數字識別碼。 Learn more about creating QR codes or explore other formats:

// QR Code for contact information
var qrCode = BarcodeWriter.CreateBarcode("BEGIN:VCARD\nFN:John Doe\nTEL:555-1234\nEND:VCARD", 
    BarcodeEncoding.QRCode, 150, 150);
qrCode.StampToExistingPdfPage("businesscard.pdf", x: 400, y: 50, pageNumber: 1);

// Data Matrix for product tracking
var dataMatrix = BarcodeWriter.CreateBarcode("PROD-2024-BATCH-789", 
    BarcodeEncoding.DataMatrix, 100, 100);
dataMatrix.StampToExistingPdfPage("product_sheet.pdf", x: 50, y: 750, pageNumber: 1);
// QR Code for contact information
var qrCode = BarcodeWriter.CreateBarcode("BEGIN:VCARD\nFN:John Doe\nTEL:555-1234\nEND:VCARD", 
    BarcodeEncoding.QRCode, 150, 150);
qrCode.StampToExistingPdfPage("businesscard.pdf", x: 400, y: 50, pageNumber: 1);

// Data Matrix for product tracking
var dataMatrix = BarcodeWriter.CreateBarcode("PROD-2024-BATCH-789", 
    BarcodeEncoding.DataMatrix, 100, 100);
dataMatrix.StampToExistingPdfPage("product_sheet.pdf", x: 50, y: 750, pageNumber: 1);
$vbLabelText   $csharpLabel

錯誤處理和最佳實踐

在進行 PDF 加蓋戳記操作時,應實施適當的錯誤處理:

try
{
    GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("DOCUMENT-ID-12345", 
        BarcodeEncoding.Code128, 200, 60);

    // Verify the PDF exists before attempting to stamp
    if (File.Exists("target.pdf"))
    {
        myBarcode.StampToExistingPdfPage("target.pdf", x: 100, y: 100, pageNumber: 1);
        Console.WriteLine("Barcode stamped successfully!");
    }
    else
    {
        Console.WriteLine("PDF file not found!");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error stamping barcode: {ex.Message}");
    // Log the error or handle it appropriately
}
try
{
    GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("DOCUMENT-ID-12345", 
        BarcodeEncoding.Code128, 200, 60);

    // Verify the PDF exists before attempting to stamp
    if (File.Exists("target.pdf"))
    {
        myBarcode.StampToExistingPdfPage("target.pdf", x: 100, y: 100, pageNumber: 1);
        Console.WriteLine("Barcode stamped successfully!");
    }
    else
    {
        Console.WriteLine("PDF file not found!");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error stamping barcode: {ex.Message}");
    // Log the error or handle it appropriately
}
$vbLabelText   $csharpLabel

性能考量

處理大型 PDF 檔案或進行多個沖壓操作時,請參考以下提示:

1.批次操作:使用 StampToExistingPdfPages() 而非循環 StampToExistingPdfPage() 2.條碼快取:建立一次即可重複使用 GeneratedBarcode 對象 3.座標計算:預先計算一致的位置座標 4.記憶體管理:分批處理超大型PDF文件

For advanced scenarios involving reading barcodes from PDFs after stamping, see our guide on reading barcodes from PDF documents.

與其他IronBarcode功能的集成

PDF 加蓋功能與其他IronBarcode功能無縫協作。 Combine it with asynchronous processing for better web application performance:

// Asynchronous PDF stamping
public async Task StampBarcodeAsync(string pdfPath, string barcodeData)
{
    await Task.Run(() =>
    {
        var barcode = BarcodeWriter.CreateBarcode(barcodeData, BarcodeEncoding.QRCode, 200, 200);
        barcode.StampToExistingPdfPage(pdfPath, x: 100, y: 100, pageNumber: 1);
    });
}
// Asynchronous PDF stamping
public async Task StampBarcodeAsync(string pdfPath, string barcodeData)
{
    await Task.Run(() =>
    {
        var barcode = BarcodeWriter.CreateBarcode(barcodeData, BarcodeEncoding.QRCode, 200, 200);
        barcode.StampToExistingPdfPage(pdfPath, x: 100, y: 100, pageNumber: 1);
    });
}
$vbLabelText   $csharpLabel

Additionally, leverage IronBarcode's image correction features when working with scanned PDFs that might need enhancement before or after barcode stamping.

常見問題排除

如果在 PDF 檔案上新增條碼時遇到問題,以下是一些解決方法:

1.座標問題:PDF 座標是從左下角開始的,而不是從左上角開始的。 2.密碼保護的PDF :確保加密PDF的密碼參數正確。

  1. Large File Sizes: For optimization and handling tips, see our troubleshooting guide
  2. Font or Encoding Issues: For special characters or Unicode, check our writing Unicode barcodes guide

遵循這些指導原則並利用 IronBarcode 的 PDF 加蓋功能,可以有效地將條碼添加到現有的 PDF 文件中,同時保持高效能和程式碼品質。

常見問題解答

如何在 C# 中將 BarCode 新增至現有的 PDF 文件?

使用 IronBarcode 的 CreateBarcode 方法生成條碼,然後應用 StampToExistingPdfPage 方法將其放置在 PDF 上。只需指定PDF文件路徑,位置坐標(x,y),以及您希望條碼出現的頁碼。

StampToExistingPdfPage 方法需要哪些參數?

IronBarcode 中的 StampToExistingPdfPage 方法需要:pdfFilePath(PDF 位置的字符串)、x 和 y 坐標(像素定位的整數)、pageNumber(整數,1-索引),以及受保護 PDF 的可選密碼參數。

我可以在 PDF 的多頁上標示相同的 BarCode 嗎?

是的,IronBarcode 提供 StampToExistingPdfPages 方法(注意复數'Pages'),它允許您在 PDF 文檔中的多個頁面上加盖一個生成的條形碼。

在 PDF 上定位 BarCode 時使用何種坐標系統?

IronBarcode 使用基於像素的坐標系統,當使用 StampToExistingPdfPage 方法時,x 坐標從頁面的左邊開始量測,y 坐標從頁面的底邊開始量測。

在現有 PDF 上標示 BarCode 的常見用例有哪些?

IronBarcode 的 PDF 燙印功能常用於在出貨標籤上加入獨特的追蹤代碼、製造報告上的批次號碼、法律表格上的文件控制號碼,以及用於數位驗證或快速存取連結的 QR 代碼。

在 PDF 上標示 BarCode 是否需要儲存中間檔案?

不,IronBarcode 的 StampToExistingPdfPage 方法可直接在 PDF 文檔上加印條形碼,而無需创建临時文件,從而节省了處理時间和存储空间。

我可以在受密碼保護的 PDF 文件上標示 BarCode 嗎?

是的,IronBarcode 支持在受密碼保护的 PDF 上加印條碼。只需在 StampToExistingPdfPage 方法中提供 PDF 密碼作為可選參數即可。

Hairil Hasyimi Bin Omar
軟體工程師
和所有优秀的工程师一样,Hairil 是個努力学习者。他正在细化自己的 C# 、Python 和 Java 知识,将这些知识應用于 Iron Software 各個团队成员以增加价值。Hairil 自马来西亚 Universiti Teknologi MARA 加入 Iron Software 团队,并以化学与工艺工程学士学位毕业。
準備好開始了嗎?
Nuget 下載 2,121,847 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。