> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/core/get-started/samples/barcodetest.md).

# Barcode Extraction

This sample shows how to use the Apryse Barcode Module to detect and extract barcodes from PDF documents.  Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB.

This sample shows how to use the Apryse Barcode Module to detect and extract barcodes from PDF documents; provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB.

{% tabs %}
{% tab title="C++" %}
{% code title="BarcodeTest.cpp" lineNumbers="true" %}

```cpp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------
#include <PDF/PDFNet.h>
#include <PDF/PDFDoc.h>
#include <PDF/BarcodeModule.h>
#include <PDF/BarcodeOptions.h>
#include <iostream>
#include <fstream>
#include "../../LicenseKey/CPP/LicenseKey.h"
using namespace std;
using namespace pdftron;
using namespace PDF;
using namespace SDF;
//---------------------------------------------------------------------------------------
// The Barcode Module is an optional PDFNet add-on that can be used to extract
// various types of barcodes from PDF documents.
//
// The Apryse SDK Barcode Module can be downloaded from https://dev.apryse.com/
//---------------------------------------------------------------------------------------
void WriteTextToFile(const std::string& filename, const UString& text)
{
	ofstream out_file(filename.c_str(), ofstream::binary);
	string out_buf = text.ConvertToUtf8();
	out_file.write(out_buf.c_str(), out_buf.size());
	out_file.close();
}

int main(int argc, char *argv[])
{
	try 
	{
		// The first step in every application using PDFNet is to initialize the 
		// library and set the path to common PDF resources. The library is usually 
		// initialized only once, but calling Initialize() multiple times is also fine.
		PDFNet::Initialize(LicenseKey);
		// The location of the Barcode Module
		PDFNet::AddResourceSearchPath("../../../Lib/");
		// Test if the add-on is installed
		if (!BarcodeModule::IsModuleAvailable())
		{
			cout << endl;
			cout << "Unable to run BarcodeTest: Apryse SDK Barcode Module not available." << endl;
			cout << "---------------------------------------------------------------" << endl;
			cout << "The Barcode Module is an optional add-on, available for download" << endl;
			cout << "at https://dev.apryse.com/. If you have already downloaded this" << endl;
			cout << "module, ensure that the SDK is able to find the required files" << endl;
			cout << "using the PDFNet::AddResourceSearchPath() function." << endl << endl;
			return 0;
		}
		// Relative path to the folder containing test files.
		string input_path =  "../../TestFiles/Barcode/";
		string output_path = "../../TestFiles/Output/";
		//--------------------------------------------------------------------------------
		// Example 1) Detect and extract all barcodes from a PDF document into a JSON file
		try
		{
			cout << "Example 1: extracting barcodes from barcodes.pdf to barcodes.json" << endl;
			// A) Open the .pdf document
			PDFDoc doc(input_path + "barcodes.pdf");
			// B) Detect PDF barcodes with the default options
			BarcodeModule::ExtractBarcodes(doc, output_path + "barcodes.json");
		}
		catch (Common::Exception& e)
		{
			cout << e << endl;
		}
		catch (...)
		{
			cout << "Unknown Exception" << endl;
		}
		//--------------------------------------------------------------------------------
		// Example 2) Limit barcode extraction to a range of pages, and retrieve the JSON into a
		// local string variable, which is then written to a file in a separate function call
		try
		{
			cout << "Example 2: extracting barcodes from pages 1-2 to barcodes_from_pages_1-2.json" << endl;
			// A) Open the .pdf document
			PDFDoc doc(input_path + "barcodes.pdf");
			// B) Detect PDF barcodes with custom options
			BarcodeOptions options;
			// Convert only the first two pages
			options.SetPages("1-2");
			UString json = BarcodeModule::ExtractBarcodesAsString(doc, options);
			// C) Save JSON to file
			WriteTextToFile(output_path + "barcodes_from_pages_1-2.json", json);
		}
		catch (Common::Exception& e)
		{
			cout << e << endl;
		}
		catch (...)
		{
			cout << "Unknown Exception" << endl;
		}
		//--------------------------------------------------------------------------------
		// Example 3) Narrow down barcode types and allow the detection of both horizontal
		// and vertical barcodes
		try
		{
			cout << "Example 3: extracting basic horizontal and vertical barcodes" << endl;
			// A) Open the .pdf document
			PDFDoc doc(input_path + "barcodes.pdf");
			// B) Detect only basic 1D barcodes, both horizontal and vertical
			BarcodeOptions options;
			// Limit extraction to basic 1D barcode types, such as EAN 13, EAN 8, UPCA, UPCE,
			// Code 3 of 9, Code 128, Code 2 of 5, Code 93, Code 11 and GS1 Databar.
			options.SetBarcodeSearchTypes(BarcodeOptions::e_linear);
			// Search for barcodes oriented horizontally and vertically
			options.SetBarcodeOrientations(
				BarcodeOptions::e_horizontal | BarcodeOptions::e_vertical);
			BarcodeModule::ExtractBarcodes(doc, output_path + "barcodes_1D.json", options);
		}
		catch (Common::Exception& e)
		{
			cout << e << endl;
		}
		catch (...)
		{
			cout << "Unknown Exception" << endl;
		}
		cout << "Done." << endl;
		PDFNet::Terminate();
	}
	catch (Common::Exception& e)	
	{
		cout << e << endl;
	}
	catch (...)
	{
		cout << "Unknown Exception" << endl;
	}
	return 0;	
}

```

{% endcode %}
{% endtab %}

{% tab title="C#" %}
{% code title="BarcodeTest.cs" lineNumbers="true" %}

```csharp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------
using System;
using pdftron;
using pdftron.Common;
using pdftron.PDF;
namespace BarcodeTestCS
{
    
    /// <summary>
    //---------------------------------------------------------------------------------------
    // The Barcode Module is an optional PDFNet add-on that can be used to extract
    // various types of barcodes from PDF documents.
    //
    // The Apryse SDK Barcode Module can be downloaded from https://dev.apryse.com/
    //---------------------------------------------------------------------------------------
    /// </summary>
    class Class1
    {
        private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
        static Class1() {}
        
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            // The first step in every application using PDFNet is to initialize the 
            // library and set the path to common PDF resources. The library is usually 
            // initialized only once, but calling Initialize() multiple times is also fine.
            PDFNet.Initialize(PDFTronLicense.Key);
            // Can optionally set path to the Barcode module
            PDFNet.AddResourceSearchPath("../../../Lib/");
            // Test if the add-on is installed
            if (!BarcodeModule.IsModuleAvailable())
            {
                Console.WriteLine("");
                Console.WriteLine("Unable to run BarcodeTest: Apryse SDK Barcode Module not available.");
                Console.WriteLine("---------------------------------------------------------------");
                Console.WriteLine("The Barcode Module is an optional add-on, available for download");
                Console.WriteLine("at https://dev.apryse.com/. If you have already downloaded this");
                Console.WriteLine("module, ensure that the SDK is able to find the required files");
                Console.WriteLine("using the PDFNet.AddResourceSearchPath() function.");
                Console.WriteLine("");
                return;
            }
            // Relative path to the folder containing test files.
            string input_path =  "../../TestFiles/Barcode/";
            string output_path = "../../TestFiles/Output/";
            //--------------------------------------------------------------------------------
            // Example 1) Detect and extract all barcodes from a PDF document into a JSON file
            try
            {
                Console.WriteLine("Example 1: extracting barcodes from barcodes.pdf to barcodes.json");
                // A) Open the .pdf document
                using (PDFDoc doc = new PDFDoc(input_path + "barcodes.pdf"))
                {
                    // B) Detect PDF barcodes with the default options
                    BarcodeModule.ExtractBarcodes(doc, output_path + "barcodes.json");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
            //--------------------------------------------------------------------------------
            // Example 2) Limit barcode extraction to a range of pages, and retrieve the JSON into a
            // local string variable, which is then written to a file in a separate function call
            try
            {
                Console.WriteLine("Example 2: extracting barcodes from pages 1-2 to barcodes_from_pages_1-2.json");
                // A) Open the .pdf document
                using (PDFDoc doc = new PDFDoc(input_path + "barcodes.pdf"))
                {
                    // B) Detect PDF barcodes with custom options
                    BarcodeOptions options = new BarcodeOptions();
                    // Convert only the first two pages
                    options.SetPages("1-2");
                    string json = BarcodeModule.ExtractBarcodesAsString(doc, options);
                    // C) Save JSON to file
                    System.IO.File.WriteAllText(output_path + "barcodes_from_pages_1-2.json", json);
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
            //--------------------------------------------------------------------------------
            // Example 3) Narrow down barcode types and allow the detection of both horizontal
            // and vertical barcodes
            try
            {
                Console.WriteLine("Example 3: extracting basic horizontal and vertical barcodes");
                // A) Open the .pdf document
                using (PDFDoc doc = new PDFDoc(input_path + "barcodes.pdf"))
                {
                    // B) Detect only basic 1D barcodes, both horizontal and vertical
                    BarcodeOptions options = new BarcodeOptions();
                    // Limit extraction to basic 1D barcode types, such as EAN 13, EAN 8, UPCA, UPCE,
                    // Code 3 of 9, Code 128, Code 2 of 5, Code 93, Code 11 and GS1 Databar.
                    options.SetBarcodeSearchTypes(BarcodeOptions.BarcodeTypeGroup.e_linear);
                    // Search for barcodes oriented horizontally and vertically
                    options.SetBarcodeOrientations(
                        BarcodeOptions.BarcodeOrientation.e_horizontal |
                        BarcodeOptions.BarcodeOrientation.e_vertical);
                    BarcodeModule.ExtractBarcodes(doc, output_path + "barcodes_1D.json", options);
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("Done.");
            PDFNet.Terminate();
        }
    }
}

```

{% endcode %}
{% endtab %}

{% tab title="Go" %}
{% code title="BarcodeTest.go" lineNumbers="true" %}

```go
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
package main
import (
	"fmt"
	"testing"
	"os"
	"flag"
	. "github.com/pdftron/pdftron-go/v2"
)
var licenseKey string
var modulePath string
func init() {
    flag.StringVar(&licenseKey, "license", "", "License key for Apryse SDK")
    flag.StringVar(&modulePath, "modulePath", "", "Path for downloaded modules")
}
//---------------------------------------------------------------------------------------
// The Barcode Module is an optional PDFNet add-on that can be used to extract
// various types of barcodes from PDF documents.
//
// The Apryse SDK Barcode Module can be downloaded from http://dev.apryse.com/
//---------------------------------------------------------------------------------------
// Relative path to the folder containing test files.
var inputPath = "../TestFiles/Barcode/"
var outputPath = "../TestFiles/Output/"
//---------------------------------------------------------------------------------------
func WriteTextToFile(outputFile string, text string) {
	f, err := os.Create(outputFile)
	if err != nil {
		fmt.Println(err)
	}
	defer f.Close()
	_, err2 := f.WriteString(text)
	if err2 != nil {
		fmt.Println(err2)
	}
}
//---------------------------------------------------------------------------------------
func TestBarcode(t *testing.T) {
    // The first step in every application using PDFNet is to initialize the
    // library and set the path to common PDF resources. The library is usually
    // initialized only once, but calling Initialize() multiple times is also fine.
    PDFNetInitialize(licenseKey)
    // The location of the Barcode Module
    PDFNetAddResourceSearchPath(modulePath)
    if ! BarcodeModuleIsModuleAvailable() {
        fmt.Println("Unable to run BarcodeTest: Apryse SDK Barcode Module not available.\n" +
        "---------------------------------------------------------------\n" +
        "The Barcode Module is an optional add-on, available for download\n" +
        "at https://dev.apryse.com/. If you have already downloaded this\n" +
        "module, ensure that the SDK is able to find the required files\n" +
        "using the PDFNetAddResourceSearchPath() function.")
    } else {
        // Example 1) Detect and extract all barcodes from a PDF document into a JSON file
        // --------------------------------------------------------------------------------
        fmt.Println("Example 1: extracting barcodes from barcodes.pdf to barcodes.json")
        // A) Open the .pdf document
        doc := NewPDFDoc(inputPath + "barcodes.pdf")
        // B) Detect PDF barcodes with the default options
        BarcodeModuleExtractBarcodes(doc, outputPath + "barcodes.json")
        doc.Close()
        // Example 2) Limit barcode extraction to a range of pages, and retrieve the JSON into a
        // local string variable, which is then written to a file in a separate function call
        // --------------------------------------------------------------------------------
        fmt.Println("Example 2: extracting barcodes from pages 1-2 to barcodes_from_pages_1-2.json")
        // A) Open the .pdf document
        doc = NewPDFDoc(inputPath + "barcodes.pdf")
        // B) Detect PDF barcodes with custom options
        options := NewBarcodeOptions()
        // Convert only the first two pages
        options.SetPages("1-2")
        json := BarcodeModuleExtractBarcodesAsString(doc, options)
        // C) Save JSON to file
        WriteTextToFile(outputPath + "barcodes_from_pages_1-2.json", json)
        doc.Close()
        // Example 3) Narrow down barcode types and allow the detection of both horizontal
        // and vertical barcodes
        // --------------------------------------------------------------------------------
        fmt.Println("Example 3: extracting basic horizontal and vertical barcodes")
        // A) Open the .pdf document
        doc = NewPDFDoc(inputPath + "barcodes.pdf")
        // B) Detect only basic 1D barcodes, both horizontal and vertical
        options = NewBarcodeOptions()
        // Limit extraction to basic 1D barcode types, such as EAN 13, EAN 8, UPCA, UPCE,
        // Code 3 of 9, Code 128, Code 2 of 5, Code 93, Code 11 and GS1 Databar.
        options.SetBarcodeSearchTypes(uint(BarcodeOptionsE_linear))
        // Search for barcodes oriented horizontally and vertically
        options.SetBarcodeOrientations(
				uint(BarcodeOptionsE_horizontal) |
				uint(BarcodeOptionsE_vertical))
        BarcodeModuleExtractBarcodes(doc, outputPath + "barcodes_1D.json", options)
        doc.Close()
	}
	PDFNetTerminate()
	fmt.Println("Done.")
}

```

{% endcode %}
{% endtab %}

{% tab title="Java" %}
{% code title="BarcodeTest.java" lineNumbers="true" %}

```java
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.pdftron.pdf.*;
import com.pdftron.common.PDFNetException;
//---------------------------------------------------------------------------------------
// The Barcode Module is an optional PDFNet add-on that can be used to extract
// various types of barcodes from PDF documents.
//
// The Apryse SDK Barcode Module can be downloaded from https://dev.apryse.com/
//---------------------------------------------------------------------------------------
public class BarcodeTest {
	static void writeTextToFile(String filename, String text) throws IOException
	{
		BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
		writer.write(text);
		writer.close();
	}
	public static void main(String[] args) {
		try {
			// The first step in every application using PDFNet is to initialize the 
			// library and set the path to common PDF resources. The library is usually 
			// initialized only once, but calling Initialize() multiple times is also fine.
			PDFNet.initialize(PDFTronLicense.Key());
			PDFNet.addResourceSearchPath("../../../Lib/");
			// Can optionally set path to the Barcode module
			if( !BarcodeModule.isModuleAvailable() )
			{
				System.out.println("");
				System.out.println("Unable to run BarcodeTest: Apryse SDK Barcode Module not available.");
				System.out.println("---------------------------------------------------------------");
				System.out.println("The Barcode Module is an optional add-on, available for download");
				System.out.println("at https://dev.apryse.com/. If you have already downloaded this");
				System.out.println("module, ensure that the SDK is able to find the required files");
				System.out.println("using the PDFNet.addResourceSearchPath() function.");
				System.out.println("");
				return;
			}
			// Relative path to the folder containing test files.
			String input_path = "../../TestFiles/Barcode/";
			String output_path = "../../TestFiles/Output/";
			//--------------------------------------------------------------------------------
			// Example 1) Detect and extract all barcodes from a PDF document into a JSON file
			System.out.println("Example 1: extracting barcodes from barcodes.pdf to barcodes.json");
				
			// A) Open the .pdf document
			try (PDFDoc doc = new PDFDoc(input_path + "barcodes.pdf"))
			{
				// B) Detect PDF barcodes with the default options
				BarcodeModule.extractBarcodes(doc, output_path + "barcodes.json");
			} catch (Exception e) {
				e.printStackTrace();
			}
			//--------------------------------------------------------------------------------
			// Example 2) Limit barcode extraction to a range of pages, and retrieve the JSON into a
			// local string variable, which is then written to a file in a separate function call
			System.out.println("Example 2: extracting barcodes from pages 1-2 to barcodes_from_pages_1-2.json");
				
			// A) Open the .pdf document
			try (PDFDoc doc = new PDFDoc(input_path + "barcodes.pdf"))
			{
				// B) Detect PDF barcodes with custom options
				BarcodeOptions options = new BarcodeOptions();
				// Convert only the first two pages
				options.setPages("1-2");
				String json = BarcodeModule.extractBarcodesAsString(doc, options);
				// C) Save JSON to file
				writeTextToFile(output_path + "barcodes_from_pages_1-2.json", json);
			} catch (Exception e) {
				e.printStackTrace();
			}
			//--------------------------------------------------------------------------------
			// Example 3) Narrow down barcode types and allow the detection of both horizontal
			// and vertical barcodes
			System.out.println("Example 3: extracting basic horizontal and vertical barcodes");
				
			// A) Open the .pdf document
			try (PDFDoc doc = new PDFDoc(input_path + "barcodes.pdf"))
			{
				// B) Detect only basic 1D barcodes, both horizontal and vertical
				BarcodeOptions options = new BarcodeOptions();
				// Limit extraction to basic 1D barcode types, such as EAN 13, EAN 8, UPCA, UPCE,
				// Code 3 of 9, Code 128, Code 2 of 5, Code 93, Code 11 and GS1 Databar.
				options.setBarcodeSearchTypes(BarcodeOptions.BarcodeTypeGroup.e_linear);
				// Search for barcodes oriented horizontally and vertically
				options.setBarcodeOrientations(
					BarcodeOptions.BarcodeOrientation.e_horizontal |
					BarcodeOptions.BarcodeOrientation.e_vertical);
				BarcodeModule.extractBarcodes(doc, output_path + "barcodes_1D.json", options);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("Done.");
			PDFNet.terminate();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
{% code title="BarcodeTest.js" lineNumbers="true" %}

```js
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------
const fs = require('fs');
const { PDFNet } = require('../../../lib/pdfnet.js');
const PDFTronLicense = require('../../LicenseKey/NODEJS/LicenseKey');
((exports) => {
	'use strict';
	//---------------------------------------------------------------------------------------
	// The Barcode Module is an optional PDFNet add-on that can be used to extract
	// various types of barcodes from PDF documents.
	//
	// The Apryse SDK Barcode Module can be downloaded from https://dev.apryse.com/
	//---------------------------------------------------------------------------------------
	exports.runBarcodeTest = () => {
		const main = async () => {
			PDFNet.addResourceSearchPath('../../../lib/');
			if (!(await PDFNet.BarcodeModule.isModuleAvailable())) {
				console.log('\nUnable to run BarcodeTest: Apryse SDK Barcode Module not available.');
				console.log('---------------------------------------------------------------');
				console.log('The Barcode Module is an optional add-on, available for download');
				console.log('at https://dev.apryse.com/. If you have already downloaded this');
				console.log('module, ensure that the SDK is able to find the required files');
				console.log('using the PDFNet.addResourceSearchPath() function.\n');
				return;
			}
			// Relative path to the folder containing test files.
			const input_path = '../../TestFiles/Barcode/';
			const output_path = '../../TestFiles/Output/';
			//--------------------------------------------------------------------------------
			// Example 1) Detect and extract all barcodes from a PDF document into a JSON file
			try {
				console.log('Example 1: extracting barcodes from barcodes.pdf to barcodes.json');
				// A) Open the .pdf document
				const doc = await PDFNet.PDFDoc.createFromFilePath(input_path + 'barcodes.pdf');
				// B) Detect PDF barcodes with the default options
				await PDFNet.BarcodeModule.extractBarcodes(doc, output_path + 'barcodes.json');
			} catch (err) {
				console.log(err);
			}
			//--------------------------------------------------------------------------------
			// Example 2) Limit barcode extraction to a range of pages, and retrieve the JSON into a
			// local string variable, which is then written to a file in a separate function call
			try {
				console.log('Example 2: extracting barcodes from pages 1-2 to barcodes_from_pages_1-2.json');
				// A) Open the .pdf document
				const doc = await PDFNet.PDFDoc.createFromFilePath(input_path + 'barcodes.pdf');
				// B) Detect PDF barcodes with custom options
				const options = new PDFNet.BarcodeModule.BarcodeOptions();
				// Convert only the first two pages
				options.setPages('1-2');
				const json = await PDFNet.BarcodeModule.extractBarcodesAsString(doc, options);
				// C) Save JSON to file
				fs.writeFileSync(output_path + 'barcodes_from_pages_1-2.json', json);
			} catch (err) {
				console.log(err);
			}
			//--------------------------------------------------------------------------------
			// Example 3) Narrow down barcode types and allow the detection of both horizontal
			// and vertical barcodes
			try {
				console.log('Example 3: extracting basic horizontal and vertical barcodes');
				// A) Open the .pdf document
				const doc = await PDFNet.PDFDoc.createFromFilePath(input_path + 'barcodes.pdf');
				// B) Detect only basic 1D barcodes, both horizontal and vertical
				const options = new PDFNet.BarcodeModule.BarcodeOptions();
				// Limit extraction to basic 1D barcode types, such as EAN 13, EAN 8, UPCA, UPCE,
				// Code 3 of 9, Code 128, Code 2 of 5, Code 93, Code 11 and GS1 Databar.
				options.setBarcodeSearchTypes(PDFNet.BarcodeModule.BarcodeOptions.BarcodeTypeGroup.e_linear);
				// Search for barcodes oriented horizontally and vertically
				options.setBarcodeOrientations(
					PDFNet.BarcodeModule.BarcodeOptions.BarcodeOrientation.e_horizontal |
					PDFNet.BarcodeModule.BarcodeOptions.BarcodeOrientation.e_vertical);
				await PDFNet.BarcodeModule.extractBarcodes(doc, output_path + 'barcodes_1D.json', options);
			} catch (err) {
				console.log(err);
			}
			//////////////////////////////////////////////////////////////////////////
			console.log('Done.');
		};
		PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error) {
			console.log('Error: ' + JSON.stringify(error));
		}).then(function(){ return PDFNet.shutdown(); });
	};
	exports.runBarcodeTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=BarcodeTest.js
```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}
{% code title="BarcodeTest.php" lineNumbers="true" %}

```php
<?php
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
include("../../../PDFNetC/Lib/PDFNetPHP.php");
include("../../LicenseKey/PHP/LicenseKey.php");
//---------------------------------------------------------------------------------------
// The Barcode Module is an optional PDFNet add-on that can be used to extract
// various types of barcodes from PDF documents.
//
// The Apryse SDK Barcode Module can be downloaded from http://dev.apryse.com/
//---------------------------------------------------------------------------------------
function WriteTextToFile($outputFile, $text)
{
	$outfile = fopen($outputFile, "w");
	fwrite($outfile, $text);
	fclose($outfile);
}
function main()
{
	// Relative path to the folder containing the test files.
	$input_path = getcwd()."/../../TestFiles/Barcode/";
	$output_path = getcwd()."/../../TestFiles/Output/";
	// The first step in every application using PDFNet is to initialize the 
	// library and set the path to common PDF resources. The library is usually 
	// initialized only once, but calling Initialize() multiple times is also fine.
	global $LicenseKey;
	PDFNet::Initialize($LicenseKey);
	PDFNet::GetSystemFontList();    // Wait for fonts to be loaded if they haven't already. This is done because PHP can run into errors when shutting down if font loading is still in progress.
	// The location of the Barcode Module
	PDFNet::AddResourceSearchPath("../../../PDFNetC/Lib/");
	if (!BarcodeModule::IsModuleAvailable()) {
		echo(nl2br("\n"));
		echo(nl2br("Unable to run BarcodeTest: Apryse SDK Barcode Module not available.\n"));
		echo(nl2br("---------------------------------------------------------------\n"));
		echo(nl2br("The Barcode Module is an optional add-on, available for download\n"));
		echo(nl2br("at https://dev.apryse.com/. If you have already downloaded this\n"));
		echo(nl2br("module, ensure that the SDK is able to find the required files\n"));
		echo(nl2br("using the PDFNet::AddResourceSearchPath() function.\n"));
		echo(nl2br("\n"));
	}
	else {
		try {
			//--------------------------------------------------------------------------------
			// Example 1) Detect and extract all barcodes from a PDF document into a JSON file
			echo(nl2br("Example 1: extracting barcodes from barcodes.pdf to barcodes.json\n"));
			// A) Open the .pdf document
			$doc = new PDFDoc($input_path."barcodes.pdf");
			// B) Detect PDF barcodes with the default options
			BarcodeModule::ExtractBarcodes($doc, $output_path."barcodes.json");
			$doc->Close();
			//--------------------------------------------------------------------------------
			// Example 2) Limit barcode extraction to a range of pages, and retrieve the JSON into a
			// local string variable, which is then written to a file in a separate function call
			echo(nl2br("Example 2: extracting barcodes from pages 1-2 to barcodes_from_pages_1-2.json\n"));
			// A) Open the .pdf document
			$doc = new PDFDoc($input_path."barcodes.pdf");
			// B) Detect PDF barcodes with custom options
			$options = new BarcodeOptions();
			// Convert only the first two pages
			$options->SetPages("1-2");
			$json = BarcodeModule::ExtractBarcodesAsString($doc, $options);
			// C) Save JSON to file
			WriteTextToFile($output_path."barcodes_from_pages_1-2.json", $json);
			$doc->Close();
			//--------------------------------------------------------------------------------
			// Example 3) Narrow down barcode types and allow the detection of both horizontal
			// and vertical barcodes
			echo(nl2br("Example 3: extracting basic horizontal and vertical barcodes\n"));
			// A) Open the .pdf document
			$doc = new PDFDoc($input_path."barcodes.pdf");
			// B) Detect only basic 1D barcodes, both horizontal and vertical
			$options = new BarcodeOptions();
			// Limit extraction to basic 1D barcode types, such as EAN 13, EAN 8, UPCA, UPCE,
			// Code 3 of 9, Code 128, Code 2 of 5, Code 93, Code 11 and GS1 Databar.
			$options->SetBarcodeSearchTypes(BarcodeOptions::e_linear);
			// Search for barcodes oriented horizontally and vertically
			$options->SetBarcodeOrientations(
				BarcodeOptions::e_horizontal |
				BarcodeOptions::e_vertical);
			BarcodeModule::ExtractBarcodes($doc, $output_path."barcodes_1D.json", $options);
			$doc->Close();
		}
		catch (Exception $e) {
			echo(nl2br("Unable to extract form fields data, error: " . $e->getMessage() . "\n"));
		}
	}
	PDFNet::Terminate();
	echo(nl2br("Done.\n"));
}
main();
?>

```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code title="BarcodeTest.py" lineNumbers="true" %}

```python
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------
import site
site.addsitedir("../../../PDFNetC/Lib")
import sys
from PDFNetPython import *
import platform
sys.path.append("../../LicenseKey/PYTHON")
from LicenseKey import *
# ---------------------------------------------------------------------------------------
# The Barcode Module is an optional PDFNet add-on that can be used to extract
# various types of barcodes from PDF documents.
#
# The Apryse SDK Barcode Module can be downloaded from http://dev.apryse.com/
# --------------------------------------------------------------------------------------
# Relative path to the folder containing the test files.
input_path = "../../TestFiles/Barcode/"
output_path = "../../TestFiles/Output/"
def WriteTextToFile(output_file, text):
    # Write the contents of text to the disk
    f = open(output_file, "w")
    try:
        f.write(text)
    finally:
        f.close()
def main():
    # The first step in every application using PDFNet is to initialize the
    # library and set the path to common PDF resources. The library is usually
    # initialized only once, but calling Initialize() multiple times is also fine.
    PDFNet.Initialize(LicenseKey)
    # The location of the Barcode Module
    PDFNet.AddResourceSearchPath("../../../PDFNetC/Lib/");
    if not BarcodeModule.IsModuleAvailable():
        print("""
        Unable to run BarcodeTest: Apryse SDK Barcode Module not available.
        ---------------------------------------------------------------
        The Barcode Module is an optional add-on, available for download
        at https://dev.apryse.com/. If you have already downloaded this
        module, ensure that the SDK is able to find the required files
        using the PDFNet.AddResourceSearchPath() function.""")
    else:
        # Example 1) Detect and extract all barcodes from a PDF document into a JSON file
        # --------------------------------------------------------------------------------
        print("Example 1: extracting barcodes from barcodes.pdf to barcodes.json")
        # A) Open the .pdf document
        doc = PDFDoc(input_path + "barcodes.pdf")
        # B) Detect PDF barcodes with the default options
        BarcodeModule.ExtractBarcodes(doc, output_path + "barcodes.json")
        doc.Close()
        # Example 2) Limit barcode extraction to a range of pages, and retrieve the JSON into a
        # local string variable, which is then written to a file in a separate function call
        # --------------------------------------------------------------------------------
        print("Example 2: extracting barcodes from pages 1-2 to barcodes_from_pages_1-2.json")
        # A) Open the .pdf document
        doc = PDFDoc(input_path + "barcodes.pdf")
        # B) Detect PDF barcodes with custom options
        options = BarcodeOptions()
        # Convert only the first two pages
        options.SetPages("1-2")
        json = BarcodeModule.ExtractBarcodesAsString(doc, options)
        # C) Save JSON to file
        WriteTextToFile(output_path + "barcodes_from_pages_1-2.json", json)
        doc.Close()
        # Example 3) Narrow down barcode types and allow the detection of both horizontal
        # and vertical barcodes
        # --------------------------------------------------------------------------------
        print("Example 3: extracting basic horizontal and vertical barcodes")
        # A) Open the .pdf document
        doc = PDFDoc(input_path + "barcodes.pdf")
        # B) Detect only basic 1D barcodes, both horizontal and vertical
        options = BarcodeOptions()
        # Limit extraction to basic 1D barcode types, such as EAN 13, EAN 8, UPCA, UPCE,
        # Code 3 of 9, Code 128, Code 2 of 5, Code 93, Code 11 and GS1 Databar.
        options.SetBarcodeSearchTypes(BarcodeOptions.e_linear)
        # Search for barcodes oriented horizontally and vertically
        options.SetBarcodeOrientations(
            BarcodeOptions.e_horizontal |
            BarcodeOptions.e_vertical)
        BarcodeModule.ExtractBarcodes(doc, output_path + "barcodes_1D.json", options)
        doc.Close()
    PDFNet.Terminate()
    print("Done.")
if __name__ == '__main__':
    main()

```

{% endcode %}
{% endtab %}

{% tab title="Ruby" %}
{% code title="BarcodeTest.rb" lineNumbers="true" %}

```ruby
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------
require '../../../PDFNetC/Lib/PDFNetRuby'
include PDFNetRuby
require '../../LicenseKey/RUBY/LicenseKey'
$stdout.sync = true
# ---------------------------------------------------------------------------------------
# The Barcode Module is an optional PDFNet add-on that can be used to extract
# various types of barcodes from PDF documents.
#
# The Apryse SDK Barcode Module can be downloaded from http://dev.apryse.com/
# --------------------------------------------------------------------------------------
# Relative path to the folder containing test files.
$input_path =  "../../TestFiles/Barcode/"
$output_path = "../../TestFiles/Output/"
def main()
	# The first step in every application using PDFNet is to initialize the 
	# library and set the path to common PDF resources. The library is usually 
	# initialized only once, but calling Initialize() multiple times is also fine.
	PDFNet.Initialize(PDFTronLicense.Key)
	
	# The location of the Barcode Module
	PDFNet.AddResourceSearchPath("../../../PDFNetC/Lib/");
	
	begin  
		if !BarcodeModule.IsModuleAvailable
			puts 'Unable to run BarcodeTest: Apryse SDK Barcode Module not available.'
			puts '---------------------------------------------------------------'
			puts 'The Barcode Module is an optional add-on, available for download'
			puts 'at https://dev.apryse.com/. If you have already downloaded this'
			puts 'module, ensure that the SDK is able to find the required files'
			puts 'using the PDFNet.AddResourceSearchPath() function.'
		else
			# Example 1) Detect and extract all barcodes from a PDF document into a JSON file
			# --------------------------------------------------------------------------------
			puts "Example 1: extracting barcodes from barcodes.pdf to barcodes.json"
			# A) Open the .pdf document
			doc = PDFDoc.new($input_path + "barcodes.pdf")
	
			# B) Detect PDF barcodes with the default options
			BarcodeModule.ExtractBarcodes(doc, $output_path + "barcodes.json")
			doc.Close
			# Example 2) Limit barcode extraction to a range of pages, and retrieve the JSON into a
			# local string variable, which is then written to a file in a separate function call
			# --------------------------------------------------------------------------------
			puts "Example 2: extracting barcodes from pages 1-2 to barcodes_from_pages_1-2.json"
			# A) Open the .pdf document
			doc = PDFDoc.new($input_path + "barcodes.pdf")
			# B) Detect PDF barcodes with custom options
			options = BarcodeOptions.new
			# Convert only the first two pages
			options.SetPages("1-2")
			json = BarcodeModule.ExtractBarcodesAsString(doc, options)
			# C) Save JSON to file
			File.open($output_path + "barcodes_from_pages_1-2.json", 'w') { |file| file.write(json) }
			doc.Close
			# Example 3) Narrow down barcode types and allow the detection of both horizontal
			# and vertical barcodes
			# --------------------------------------------------------------------------------
			puts "Example 3: extracting basic horizontal and vertical barcodes"
			# A) Open the .pdf document
			doc = PDFDoc.new($input_path + "barcodes.pdf")
			# B) Detect only basic 1D barcodes, both horizontal and vertical
			options = BarcodeOptions.new
			# Limit extraction to basic 1D barcode types, such as EAN 13, EAN 8, UPCA, UPCE,
			# Code 3 of 9, Code 128, Code 2 of 5, Code 93, Code 11 and GS1 Databar.
			options.SetBarcodeSearchTypes(BarcodeOptions::E_linear)
			# Search for barcodes oriented horizontally and vertically
			options.SetBarcodeOrientations(
				BarcodeOptions::E_horizontal |
				BarcodeOptions::E_vertical)
			BarcodeModule.ExtractBarcodes(doc, $output_path + "barcodes_1D.json", options)
			doc.Close
		end
	rescue => error
		puts "Unable to extract barcodes, error: " + error.message
	end
	PDFNet.Terminate
	puts "Done."
end
main()

```

{% endcode %}
{% endtab %}

{% tab title="VB" %}
{% code title="BarcodeTest.vb" lineNumbers="true" %}

```vb
'---------------------------------------------------------------------------------------
' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
' Consult legal.txt regarding legal and license information.
'---------------------------------------------------------------------------------------
Imports System
Imports pdftron
Imports pdftron.Common
Imports pdftron.PDF
' <summary>
'---------------------------------------------------------------------------------------
' The Barcode Module is an optional PDFNet add-on that can be used to extract
' various types of barcodes from PDF documents.
'
' The Apryse SDK Barcode Module can be downloaded from https://dev.apryse.com/
'---------------------------------------------------------------------------------------
' </summary>
Module BarcodeTestVB
    Dim pdfNetLoader As PDFNetLoader
    Sub New()
        pdfNetLoader = pdftron.PDFNetLoader.Instance()
    End Sub
    ' The main entry point for the application.
    Sub Main()
        ' The first step in every application using PDFNet is to initialize the 
        ' library and set the path to common PDF resources. The library is usually 
        ' initialized only once, but calling Initialize() multiple times is also fine.
        PDFNet.Initialize(PDFTronLicense.Key)
        ' Can optionally set path to the Barcode module
        PDFNet.AddResourceSearchPath("../../../../../Lib/")
        ' Test if the add-on is installed
        If Not BarcodeModule.IsModuleAvailable() Then
            Console.WriteLine("")
            Console.WriteLine("Unable to run BarcodeTest: Apryse SDK Barcode Module not available.")
            Console.WriteLine("---------------------------------------------------------------")
            Console.WriteLine("The Barcode Module is an optional add-on, available for download")
            Console.WriteLine("at https://dev.apryse.com/. If you have already downloaded this")
            Console.WriteLine("module, ensure that the SDK is able to find the required files")
            Console.WriteLine("using the PDFNet.AddResourceSearchPath() function.")
            Console.WriteLine("")
            Return
        End If
        ' Relative path to the folder containing test files.
        Dim input_path As String = "../../../../TestFiles/Barcode/"
        Dim output_path As String = "../../../../TestFiles/Output/"
        '--------------------------------------------------------------------------------
        ' Example 1) Detect and extract all barcodes from a PDF document into a JSON file
        Try
            Console.WriteLine("Example 1: extracting barcodes from barcodes.pdf to barcodes.json")
            ' A) Open the .pdf document
            Using doc As PDFDoc = New PDFDoc(input_path & "barcodes.pdf")
                ' B) Detect PDF barcodes with the default options
                BarcodeModule.ExtractBarcodes(doc, output_path & "barcodes.json")
            End Using
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try
        '--------------------------------------------------------------------------------
        ' Example 2) Limit barcode extraction to a range of pages, and retrieve the JSON into a
        ' local string variable, which is then written to a file in a separate function call
        Try
            Console.WriteLine("Example 2: extracting barcodes from pages 1-2 to barcodes_from_pages_1-2.json")
            ' A) Open the .pdf document
            Using doc As PDFDoc = New PDFDoc(input_path & "barcodes.pdf")
                ' B) Detect PDF barcodes with custom options
                Dim options As BarcodeOptions = New BarcodeOptions()
                ' Convert only the first two pages
                options.SetPages("1-2")
                Dim json As String = BarcodeModule.ExtractBarcodesAsString(doc, options)
                ' C) Save JSON to file
                System.IO.File.WriteAllText(output_path & "barcodes_from_pages_1-2.json", json)
            End Using
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try
        '--------------------------------------------------------------------------------
        ' Example 3) Narrow down barcode types and allow the detection of both horizontal
        ' and vertical barcodes
        Try
            Console.WriteLine("Example 3: extracting basic horizontal and vertical barcodes")
            ' A) Open the .pdf document
            Using doc As PDFDoc = New PDFDoc(input_path & "barcodes.pdf")
                ' B) Detect only basic 1D barcodes, both horizontal and vertical
                Dim options As BarcodeOptions = New BarcodeOptions()
                ' Limit extraction to basic 1D barcode types, such as EAN 13, EAN 8, UPCA, UPCE,
                ' Code 3 of 9, Code 128, Code 2 of 5, Code 93, Code 11 and GS1 Databar.
                options.SetBarcodeSearchTypes(BarcodeOptions.BarcodeTypeGroup.e_linear)
                ' Search for barcodes oriented horizontally and vertically
                options.SetBarcodeOrientations(BarcodeOptions.BarcodeOrientation.e_horizontal Or BarcodeOptions.BarcodeOrientation.e_vertical)
                BarcodeModule.ExtractBarcodes(doc, output_path & "barcodes_1D.json", options)
            End Using
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try
        Console.WriteLine("Done.")
        PDFNet.Terminate()
    End Sub
End Module

```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/core/get-started/samples/barcodetest.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
