Cómo Leer Códigos de Barras Desde PDFs en C#

How to read Barcodes from PDF Documents

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

Reading barcodes from PDF documents is detecting and decoding barcodes present within the pages of a PDF file. Instead of manually scanning a printed barcode, this technology allows for the direct extraction of the encoded information from a digital document. This is particularly useful for automating workflows that involve processing invoices, shipping labels, reports, and other documents that use barcodes to store data.

Quickstart: Reading Barcodes Directly from a PDF)

Jump right in by using IronBarcode’s ReadPdf method — it reads barcodes from PDFs instantly without converting to images first. With just one line of code, you can extract barcode data quickly and start building more advanced options if needed.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode

  2. Copy and run this code snippet.

    var results = IronBarCode.BarcodeReader.ReadPdf("invoice.pdf");
  3. Deploy to test on your live environment

    Start using IronBarcode in your project today with a free trial
    arrow pointer

as-heading:3(Overview: Minimal Workflow

  1. Install the barcode library to process barcode files.
  2. Create PdfBarcodeReaderOptions if required.
  3. Use the ReadPdf method from BarcodeReader to read barcodes from PDFs.
  4. Specify additional barcode reading options using BarcodeReaderOption.
  5. Extract barcode values.

Read Barcodes from PDF Documents directly

Apart from IronBarcodes' ability to read barcodes from images, IronBarcode also takes pride in its ability to read barcodes from PDF documents. This saves users from the hassle of converting PDF documents into images before feeding them into IronBarcode for reading. Since PDF documents are more intricate and different from images, a different read method should also be used, and that is the BarcodeReader.ReadPdf() method. This method accepts various types of PDF document input, including:

  • byte[] array: PDF document as a byte array.
  • IEnumerable<Byte[]>: PDF documents as byte arrays stored in a collection.
  • MemoryStream: PDF documents as MemoryStream type.
  • IEnumerable<Stream>: PDF documents as a collection of MemoryStream.
  • String: PDF document path as a string. If the PDF document is already copied into the project, this would be the name of the PDF document in a string.
  • IEnumerable<String>: PDF document path/name strings stored in a collection.

Apart from the types of input mentioned above, BarcodeReader.ReadPdf() also accepts PdfBarcodeReaderOptions for more advanced/improved reading which we will discuss in the next subtopic. Now, let us see the code snippet below that demonstrates the use of the BarcodeReader.ReadPdf() method to read barcodes in PDF documents.

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-pdf-1.cs
using IronBarCode;
using System;
using System.Collections.Generic;

List<String> docs = new List<String>();
docs.Add(@"pdf_a.pdf");
docs.Add(@"pdf_b.pdf");

var myBarcode = BarcodeReader.ReadPdfs(docs);   //can also accept individual PDF document file path as argument

foreach (var value in myBarcode)
{
    Console.WriteLine(value.ToString());
}
Imports IronBarCode
Imports System
Imports System.Collections.Generic

Private docs As New List(Of String)()
docs.Add("pdf_a.pdf")
docs.Add("pdf_b.pdf")

Dim myBarcode = BarcodeReader.ReadPdfs(docs) 'can also accept individual PDF document file path as argument

For Each value In myBarcode
	Console.WriteLine(value.ToString())
Next value
$vbLabelText   $csharpLabel

From the code snippet above, we can see that to read barcodes using IronBarcode, we can simply add the file path string of the PDF document into the BarcodeReader.ReadPdf() method to read the barcode value and store the result in a variable. If you wish to print the values of all the barcodes found in the PDF document onto the console, just use a foreach loop to iterate and print every element found in the variable by calling the ToString() method on them. On top of that, the code snippet above also demonstrates using a collection of PDF document names as an argument in BarcodeReader.ReadPdf().

Reading Multiple PDFs at once

Aside from adding each PDF to the array individually, IronBarCode also introduces a ReadPdfs method that allows developers to quickly read through a list of PDFs. This is useful when there are multiple PDFs from which you want to extract the barcode and avoids adding them one by one. Let's take a look at an example below.

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-pdf-read-from-multiple-pdf.cs
using IronBarCode;
using System;
using System.Collections.Generic;
using System.IO;

// Get all PDF files from a directory and add to list
string folderPath = @"PATH_TO_YOUR_FOLDER";
List<string> docs = new List<string>(Directory.GetFiles(folderPath, "*.pdf"));

// Read barcodes from all PDFs
var docResult = BarcodeReader.ReadPdfs(docs);

// Print results
foreach (var doc in docResult)
{
    foreach (var item in doc)
    {
        Console.WriteLine("Barcode " + item.ToString() + " found at page " + item.PageNumber);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

In the code above, we first obtain all PDF files from a directory, then add them to the List<string>, then call ReadPdfs and put docs as our input parameter. The ReadPdfs then returns an array of BarcodeResults. Finally, we loop through the docResult and print out the barcodes found in each PDF.

Setting PDF Barcode Reader Options

Similar to reading barcodes from images, reading barcodes from PDF documents also allows users to tweak or adjust the properties in the barcode reader called PdfBarcodeReaderOptions. Adjusting the properties in PdfBarcodeReaderOptions will greatly help in reading quality, accuracy, and performance. All the adjustable properties in BarcodeReaderOptions are inherited in PdfBarcodeReaderOptions, with some additional properties for PDF documents. Users can specify the page number or collection of page numbers from the PDF document in which they want the PdfBarcodeReaderOptions to apply when instantiating a new instance of PdfBarcodeReaderOptions. The code snippet below demonstrates:

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-pdf-2.cs
using IronBarCode;
using System.Collections.Generic;

List<int> pageNumber = new List<int>() { 1, 2, 3 };

PdfBarcodeReaderOptions PdfOptions = new PdfBarcodeReaderOptions(pageNumber)  // can also use individual page number as argument
{
    // Properties of PDF Barcode reader options
};
Imports IronBarCode
Imports System.Collections.Generic

Private pageNumber As New List(Of Integer)() From {1, 2, 3}

Private PdfOptions As New PdfBarcodeReaderOptions(pageNumber)
$vbLabelText   $csharpLabel

Now let us discover the additional properties in PdfBarcodeReaderOptions available to manipulate, aside from those available in BarcodeReaderOptions.

DPI

Users can specify the DPI or Dots Per Inch of the barcode image in a PDF document. This will help in reading a low-quality barcode image in a PDF document. This property can be set using an Integer value.

PageNumbers

If users know beforehand the page number that contains the barcode that needs to be read in a PDF document, they can specify it in this property. Doing this will greatly improve the reading performance of IronBarcode, especially for PDF documents that have many pages, since IronBarcode would not need to read all pages or pages that do not have barcodes to be read. This property is 1-based, meaning the first page of the PDF document is 1 instead of 0.

Password

As the name suggests, this property enables users to work with encrypted PDF files that require password input to access the contents of the PDF document. Kindly note however, IronBarcode will not be able to provide the PDF document's password. This property will accept a String input.

Scale

This property enables users to control the scale factor for scaling width and height when converting to an Image. This property accepts an Integer as a value, and the default value for this property is 3.5. Setting this property will help in reading small barcodes present in a PDF document, as scaling up will zoom the PDF document.

Advanced Barcode Reading from PDF Document

Now that we know the properties in PdfBarcodeReaderOptions available for adjustments and tweaks, let us see how to apply them in the project for reading barcodes in a PDF document.

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-pdf-3.cs
using IronBarCode;
using System;
using System.Collections.Generic;

List<int> pageNumber = new List<int>() { 1, 2, 3 };

PdfBarcodeReaderOptions PdfOptions = new PdfBarcodeReaderOptions(pageNumber)
{
    DPI = 150,
    //PageNumbers = pageNumber,      //this property is not needed if page numbers has been specified as the argument in PdfBarcodeReaderOptions
    Password = "barcode",
    Scale = 3.5,
    //properties below are some of the properties inherited from BarcodeReaderOptions
    Speed = ReadingSpeed.Detailed,
    ExpectBarcodeTypes = BarcodeEncoding.Code93,
    ExpectMultipleBarcodes = true
};

var myBarcode = BarcodeReader.ReadPdf(@"pdf_a_filepath.pdf", PdfOptions);
foreach (var value in myBarcode)
{
    Console.WriteLine(value.ToString());
}
Imports IronBarCode
Imports System
Imports System.Collections.Generic

Private pageNumber As New List(Of Integer)() From {1, 2, 3}

Private PdfOptions As New PdfBarcodeReaderOptions(pageNumber) With {
	.DPI = 150,
	.Password = "barcode",
	.Scale = 3.5,
	.Speed = ReadingSpeed.Detailed,
	.ExpectBarcodeTypes = BarcodeEncoding.Code93,
	.ExpectMultipleBarcodes = True
}

Private myBarcode = BarcodeReader.ReadPdf("pdf_a_filepath.pdf", PdfOptions)
For Each value In myBarcode
	Console.WriteLine(value.ToString())
Next value
$vbLabelText   $csharpLabel

The code snippet above demonstrates how to implement PdfBarcodeReaderOptions properties in IronBarcode. The PdfBarcodeReaderOptions first needs to be initialized with a variable name before accessing and adjusting the properties. In the code snippet, we can see that the list of page numbers of the PDF document was used as an argument when initializing PdfBarcodeReaderOptions. This specifies the page number that we want the settings of PdfBarcodeReader to apply. Users can also specify the PDF page number in the PdfBarcodeReaderOptions property as PageNumbers.

On the other hand, we can also see that we can use properties from BarcodeReaderOptions such as ExpectMultipleBarcodes and ExpectBarcodeTypes in PdfBarcodeReaderOptions since they are inherited from the original class. This will greatly help in overall reading performance and accuracy. To apply the set properties of PdfBarcodeReaderOptions in the barcode read, input the variable name of the PdfBarcodeReaderOptions class we created as the second argument in the BarcodeReader.ReadPdf() method, with the PDF document to be read file path as the first argument.

Preguntas Frecuentes

¿Cómo leo códigos de barras de documentos PDF?

Puedes leer códigos de barras de documentos PDF utilizando el método `ReadPdf` de la clase `BarcodeReader` en una aplicación .NET. Este método acepta entradas como arreglos de bytes, flujos de memoria y rutas de archivos.

¿Cuáles son las ventajas de usar PdfBarcodeReaderOptions?

PdfBarcodeReaderOptions proporciona configuraciones para mejorar la calidad y precisión de la lectura de códigos de barras, como ajustar el DPI, especificar números de página y manejar PDFs encriptados con una contraseña.

¿Puedo leer códigos de barras de documentos PDF encriptados?

Sí, puedes leer códigos de barras de documentos PDF encriptados utilizando la propiedad Password en PdfBarcodeReaderOptions para proporcionar la contraseña necesaria.

¿Cómo puedo mejorar la eficiencia de la lectura de códigos de barras de PDFs?

Mejora la eficiencia utilizando PdfBarcodeReaderOptions para especificar números de página y ajustar el factor de escala, lo que reduce la necesidad de convertir PDFs en imágenes, ahorrando tiempo y recursos.

¿Qué formatos de entrada acepta el método ReadPdf?

El método `ReadPdf` acepta varios formatos de entrada, incluidos arreglos byte[], MemoryStream y rutas de archivos en forma de cadena.

¿Es posible leer múltiples códigos de barras de un solo archivo PDF?

Sí, al configurar la propiedad ExpectMultipleBarcodes en PdfBarcodeReaderOptions, puedes leer múltiples códigos de barras de un solo archivo PDF.

¿Cómo puedo especificar la resolución para leer códigos de barras en PDFs?

Especifica la resolución configurando la propiedad DPI en PdfBarcodeReaderOptions a tu valor entero deseado para controlar la calidad del escaneo.

¿Cuál es el papel del factor de escala en la lectura de códigos de barras de PDFs?

El factor de escala, que por defecto es 3.5, se usa para convertir un PDF en una imagen, afectando la calidad y el rendimiento de la lectura de códigos de barras.

¿Puedo usar una biblioteca de códigos de barras .NET para leer códigos de barras de imágenes?

Sí, una biblioteca de códigos de barras .NET como IronBarcode puede leer códigos de barras tanto de imágenes como de archivos PDF, utilizando métodos específicos para cada formato.

¿Qué debo hacer si la lectura de códigos de barras no es lo suficientemente precisa?

Si la lectura de códigos de barras no es precisa, ajusta las opciones de PdfBarcodeReaderOptions cambiando el DPI, el factor de escala o especificando los números de página correctos para mejorar la calidad.

Hairil Hasyimi Bin Omar
Ingeniero de Software
Como todos los grandes ingenieros, Hairil es un ávido aprendiz. Está refinando su conocimiento de C#, Python y Java, usando ese conocimiento para agregar valor a los miembros del equipo en Iron Software. Hairil se unió al equipo de Iron Software desde la Universiti Teknologi MARA en Malasia, donde se ...
Leer más
¿Listo para empezar?
Nuget Descargas 1,935,276 | Versión: 2025.11 recién lanzado