Add Barcode to PDF Pages Using iTextSharp and VB.NET

I was tasked to convert any documents to PDF and add user generated barcode in each page. Using iTextsharp.dll, I finally managed to place barcodes along the top left side of the target PDF pages.

Using iTextsharp.dll to manipulate an existing PDF file and a procedure of adding watermark images that I found while searching the web. I combined the two and I came up with this.

Imports System
Imports System.IO
Imports System.Windows.Forms
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Public Shared Sub AddBarCodePerPage(ByVal sourceFile As String, ByVal outputFile As String, ByVal BarcodeValue As String, ByVal XPos As Single, ByVal YPos As Single, _
Optional ByVal BarHeight As Single = 25)

Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim stamper As iTextSharp.text.pdf.PdfStamper = Nothing
Dim cb As iTextSharp.text.pdf.PdfContentByte = Nothing
Dim rect As iTextSharp.text.Rectangle = Nothing
Dim pageCount As Integer = 0
Dim X1, Y1 As Single

Dim BImage As iTextSharp.text.Image
Dim bc39 As New Barcode39()

bc39.Code = BarcodeValue
bc39.BarHeight = BarHeight
bc39.Extended = True

reader = New iTextSharp.text.pdf.PdfReader(sourceFile)
rect = reader.GetPageSizeWithRotation(1)
stamper = New iTextSharp.text.pdf.PdfStamper(reader, New System.IO.FileStream(outputFile, IO.FileMode.Create))

pageCount = reader.NumberOfPages()
For i As Integer = 1 To pageCount
cb = stamper.GetOverContent(i)
BImage = bc39.CreateImageWithBarcode(cb, Nothing, Nothing)

If BImage.Width > rect.Width OrElse BImage.Height > rect.Height Then
BImage.ScaleToFit(rect.Width, rect.Height)
X1 = XPos
Y1 = (rect.Height - BImage.ScaledHeight) - YPos
X1 = XPos
Y1 = (rect.Height - BImage.Height) - YPos
End If

BImage.SetAbsolutePosition(X1, Y1)
Catch ex As Exception
End Try
End Sub

Don’t forget to reference iTextSharp on your project.

One comment on “Add Barcode to PDF Pages Using iTextSharp and VB.NET

  1. We are Protex Smart Technologies Co.,Ltd. As one of China’s best suppliers of barcode ribbons and labels , we can provide you products with lowest price and excellent quality. Please feel free to contact us directly. Thank you very much


Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>