How to Stamp Barcodes on PDFs Using C#
Stamp barcodes onto existing PDF documents in C# using IronBarcode's CreateBarcode method with StampToExistingPdfPage for single pages or StampToExistingPdfPages for multiple pages, specifying coordinates and page numbers.
This example demonstrates generating a barcode using IronBarcode's CreateBarcode and stamping it onto an existing PDF page. Supply the PDF path, position coordinates, and page number.
-
1Install IronBarcode with NuGet Package Manager
-
2Copy and run this code snippet.
IronBarCode.BarcodeWriter.CreateBarcode("https://my.site", IronBarCode.BarcodeEncoding.QRCode, 150, 150) .StampToExistingPdfPage("report.pdf", x: 50, y: 50, pageNumber: 1);C# -
3Deploy to test on your live environment
Start using IronBarcode in your project today with a free trial
StampToExistingPdfPage
StampToExistingPdfPages
Minimal Workflow (5 steps)
- Download C# library to stamp barcode on PDF
- Create a barcode with a specified barcode type and value
- Specify the barcode size
- Utilize the
StampToExistingPdfPagemethod to stamp the barcode on a single PDF page - Use the
StampToExistingPdfPagesmethod to stamp the barcode on multiple PDF pages
How Do I Stamp a Barcode on an Existing PDF Page?
Apart from exporting barcodes as PDF, IronBarcode enables stamping the GeneratedBarcode directly onto existing PDF documents. This feature is useful when adding tracking codes, inventory labels, or document identifiers to existing reports, invoices, or forms. The following code snippet demonstrates this task.
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");Imports IronBarCode
Private myBarcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.Code128, 200, 100)
myBarcode.StampToExistingPdfPage("pdf_file_path.pdf", x:= 200, y:= 100, 3, "password")What Parameters Does StampToExistingPdfPage Require?
StampToExistingPdfPage()
GeneratedBarcode
The code snippet calls the StampToExistingPdfPage method to stamp the object onto the PDF document. This method provides flexibility while maintaining simplicity. Below are the method parameters:
pdfFilePath: A System.String representing the PDF document path (relative or absolute).x: A System.Double for horizontal position in pixels from the left edge.y: A System.Double for vertical position in pixels from the bottom edge.pageNumber: A System.Int32 indicating the page (1-indexed, first page is 1).password: A System.String for password-protected PDFs (optional).
When Should I Use StampToExistingPdfPage?
Running the code snippet stamps the GeneratedBarcode directly into the PDF document without intermediate saving. This method suits scenarios requiring:
StampToExistingPdfPages()
GeneratedBarcode
- Unique tracking codes on shipping labels or delivery documents
- Batch numbers on manufacturing reports
- Document control numbers on legal or regulatory forms
- QR codes for digital authentication or quick access links
The direct stamping approach saves processing time and eliminates temporary files. For information on different barcode types, see the supported barcode formats guide.
How Do I Stamp a Barcode on Multiple PDF Pages?
Sometimes the same barcode needs stamping on multiple pages. Common uses include applying document identifiers to every page of multi-page reports, adding version control codes throughout technical documents, or inserting security barcodes on each page of confidential materials. Instead of looping the single-page method, use the StampToExistingPdfPages method on the GeneratedBarcode object. The following code snippet demonstrates this method.
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");Imports IronBarCode
Imports System.Collections.Generic
Private myBarcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.Code128, 200, 100)
Private pages As New List(Of Integer)()
pages.Add(1)
pages.Add(2)
pages.Add(3)
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x:= 200, y:= 100, pages, "password")For flexibility, use LINQ to generate page ranges dynamically:
// 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");Imports System.Linq
' Stamp on all even pages from 2 to 10
Dim evenPages = Enumerable.Range(1, 10).Where(Function(x) x Mod 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
Dim selectedPages = New List(Of Integer) From {1, 2, 3, 18, 19, 20}
myBarcode.StampToExistingPdfPages("pdf_file_path.pdf", x:=200, y:=100, selectedPages, "password")What Parameters Does StampToExistingPdfPages Accept?
Below are the method parameters:
pdfFilePath: A System.String representing the PDF document path.x: A System.Double for horizontal position in pixels.y: A System.Double for vertical position in pixels.pageNumbers: AnIEnumerable<System.Int32>of pages to stamp (1-indexed).password: A System.String for password-protected PDFs (optional).
StampToExistingPdfPages()
StampToExistingPdfPage()
GeneratedBarcode
Why Use StampToExistingPdfPages Instead of Looping?
This method provides efficient barcode stamping on multiple pages without manual iteration, improving code readability and performance. The internal implementation optimizes PDF processing, resulting in:
- Faster execution: PDF opened and processed once, not multiple times
- Lower memory usage: Efficient resource management for large PDFs
- Cleaner code: No manual loop and error handling management
- Atomic operations: All pages stamped in single operation
Advanced Stamping Techniques
Customizing Barcode Appearance Before Stamping
Before stamping your barcode onto a PDF, customize its appearance. 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.ChangeBarCodeColor(IronSoftware.Drawing.Color.DarkBlue);
// Now stamp the customized barcode
myBarcode.StampToExistingPdfPage("invoice.pdf", x: 450, y: 700, pageNumber: 1);
Working with Different Barcode Types
Different scenarios require different barcode types. QR codes suit URLs and large data sets, while Code128 works for alphanumeric identifiers. 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
Dim qrCode = BarcodeWriter.CreateBarcode("BEGIN:VCARD" & vbLf & "FN:John Doe" & vbLf & "TEL:555-1234" & vbLf & "END:VCARD",
BarcodeEncoding.QRCode, 150, 150)
qrCode.StampToExistingPdfPage("businesscard.pdf", x:=400, y:=50, pageNumber:=1)
' Data Matrix for product tracking
Dim dataMatrix = BarcodeWriter.CreateBarcode("PROD-2024-BATCH-789",
BarcodeEncoding.DataMatrix, 100, 100)
dataMatrix.StampToExistingPdfPage("product_sheet.pdf", x:=50, y:=750, pageNumber:=1)Error Handling and Best Practices
Implement proper error handling when working with PDF stamping operations:
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
}Imports System
Imports System.IO
Try
Dim myBarcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("DOCUMENT-ID-12345", BarcodeEncoding.Code128, 200, 60)
' Verify the PDF exists before attempting to stamp
If File.Exists("target.pdf") Then
myBarcode.StampToExistingPdfPage("target.pdf", x:=100, y:=100, pageNumber:=1)
Console.WriteLine("Barcode stamped successfully!")
Else
Console.WriteLine("PDF file not found!")
End If
Catch ex As Exception
Console.WriteLine($"Error stamping barcode: {ex.Message}")
' Log the error or handle it appropriately
End TryPerformance Considerations
When working with large PDFs or multiple stamping operations, consider these tips:
- Batch Operations: Use
StampToExistingPdfPagesinstead of loopingStampToExistingPdfPage - Barcode Caching: Create once and reuse the
GeneratedBarcodeobject - Coordinate Calculation: Pre-calculate consistent position coordinates
- Memory Management: Process very large PDFs in batches
For advanced scenarios involving reading barcodes from PDFs after stamping, see our guide on reading barcodes from PDF documents.
Integration with Other IronBarcode Features
PDF stamping functionality works seamlessly with other IronBarcode features. 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);
});
}Imports System.Threading.Tasks
' Asynchronous PDF stamping
Public Async Function StampBarcodeAsync(pdfPath As String, barcodeData As String) As Task
Await Task.Run(Sub()
Dim barcode = BarcodeWriter.CreateBarcode(barcodeData, BarcodeEncoding.QRCode, 200, 200)
barcode.StampToExistingPdfPage(pdfPath, x:=100, y:=100, pageNumber:=1)
End Sub)
End FunctionAdditionally, leverage IronBarcode's image correction features when working with scanned PDFs that might need enhancement before or after barcode stamping.
Troubleshooting Common Issues
If encountering issues while stamping barcodes on PDFs, here are solutions:
- Coordinate Issues: PDF coordinates start from bottom-left corner, not top-left
- Password-Protected PDFs: Ensure correct password parameter for encrypted PDFs
- Large File Sizes: For optimization and handling tips, see our troubleshooting guide
- Font or Encoding Issues: For special characters or Unicode, check our writing Unicode barcodes guide
Following these guidelines and leveraging IronBarcode's PDF stamping capabilities enables efficient barcode addition to existing PDF documents while maintaining high performance and code quality.
Frequently Asked Questions
What is the primary method for stamping a barcode on a PDF using IronBarcode?
The primary method for stamping a barcode on a PDF using IronBarcode is the `StampToExistingPdfPage` method.
Can IronBarcode stamp barcodes on multiple PDF pages at once?
Yes, IronBarcode supports stamping barcodes on multiple PDF pages using the `StampToExistingPdfPages` method.
What are some common use cases for stamping barcodes on PDFs?
Common use cases for stamping barcodes on PDFs include adding tracking codes, inventory labels, or document identifiers to reports, invoices, or forms.
How do you specify the position of a barcode on a PDF page in IronBarcode?
In IronBarcode, you specify the position of a barcode on a PDF page using the `x` and `y` parameters, which represent the coordinates in pixels.
Does IronBarcode support password-protected PDFs when stamping barcodes?
Yes, IronBarcode supports password-protected PDFs. You can provide a password as an optional parameter when using the `StampToExistingPdfPage` or `StampToExistingPdfPages` methods.
What barcode types can be generated with IronBarcode for PDF stamping?
IronBarcode can generate various barcode types, including QR codes and Code128, which can be stamped onto PDFs.
How can you customize the appearance of a barcode before stamping it on a PDF in IronBarcode?
You can customize the appearance of a barcode in IronBarcode using methods such as `AddAnnotationTextAboveBarcode`, `AddAnnotationTextBelowBarcode`, and `ChangeBarCodeColor` before stamping.
Why should you use the StampToExistingPdfPages method instead of looping for multiple pages?
The `StampToExistingPdfPages` method is preferred for stamping on multiple pages because it is more efficient, reduces processing time, and optimizes resource usage compared to manually looping through pages.
Are there performance considerations when stamping barcodes on large PDFs with IronBarcode?
Yes, when stamping barcodes on large PDFs, it's recommended to use batch operations, cache barcodes, and manage memory efficiently for better performance with IronBarcode.
What should be done if a barcode stamping operation fails in IronBarcode?
If a barcode stamping operation fails, implement error handling using `try-catch` blocks to log errors and ensure that the PDF file exists before stamping with IronBarcode.
