Last updated: February 5, 2025

<span aria-hidden="true" id="building-a-document-ocr-tool-using-gcp-ocr-and-nodejs"></span>

# Building a document OCR tool using GCP OCR and Node.js

![Tim Koschützki](/assets/images/teammates/avatar-tim-kos-1.jpg?dpl=dpl_AkBKiiEcd5MPUBn4NARw15mr6FeE)

**Tim Koschützki**

Co-founder · Berlin, Germany · Show bio

[](https://x.com/tim%5Fkos)[](https://github.com/tim-kos)

Optical Character Recognition (OCR) unlocks text content within images and PDFs, enabling features like searchable documents, automated data entry, and content analysis. In this DevTip, we'll build a document OCR tool using GCP OCR and Node.js to efficiently extract text from images and PDFs in your applications.

<span aria-hidden="true" id="introduction"></span>

## Introduction

[GCP OCR⁠](https://cloud.google.com/vision/docs/ocr), powered by the Google Cloud Vision API, provides robust image analysis capabilities, including OCR for text extraction. Integrating this service into your Node.js application allows you to process images and PDFs programmatically and extract text data efficiently.

This guide walks you through setting up the Google Cloud Vision API, authenticating your application, and writing Node.js code to perform OCR on images and PDFs.

<span aria-hidden="true" id="prerequisites"></span>

## Prerequisites

Ensure you have the following:

* A [Google Cloud Platform⁠](https://cloud.google.com/) (GCP) account
* [Node.js⁠](https://nodejs.org/en/) version 18 or later installed
* Basic knowledge of JavaScript and Node.js

<span aria-hidden="true" id="setting-up-google-cloud-vision-api"></span>

## Setting up Google Cloud Vision API

### 1. Create a GCP project

1. Go to the [Google Cloud Console⁠](https://console.cloud.google.com/).
2. Click on the project dropdown and select **New Project**.
3. Enter a project name and click **Create**.

### 2. Enable the vision API

1. In the Cloud Console, navigate to **APIs & Services** > **Library**.
2. Search for **Cloud Vision API**.
3. Click on **Cloud Vision API** and then click **Enable**.

<span aria-hidden="true" id="authentication-setup"></span>

### Authentication setup

1. Create a service account key:
   * Go to **IAM & Admin** > **Service Accounts**
   * Create a new service account or select an existing one
   * Create a new key (JSON format)
   * Download and securely store the JSON key file
2. Set up authentication in your application:

```javascript
const vision = require('@google-cloud/vision')  
const client = new vision.ImageAnnotatorClient({  
  keyFilename: 'path/to/your/service-account-key.json',  
})  
```

Or use environment variables:

```bash
export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/service-account-key.json"  
```

<span aria-hidden="true" id="installing-the-google-cloud-vision-client-library"></span>

## Installing the Google cloud vision client library

Initialize a new Node.js project and install the necessary library:

```bash
mkdir ocr-project
cd ocr-project
npm init -y
npm install @google-cloud/vision@4.3.2 # Latest stable version as of March 2024

```

<span aria-hidden="true" id="writing-the-nodejs-code"></span>

## Writing the Node.js code

Create an `index.js` file in your project directory:

```javascript
// index.js

const vision = require('@google-cloud/vision');
const path = require('path');
const fs = require('fs');

// Creates a client
const client = new vision.ImageAnnotatorClient({
  keyFilename: path.join(__dirname, 'path/to/your/service-account-key.json'),
});

async function extractTextFromImage(imagePath) {
  try {
    const [result] = await client.textDetection(imagePath);
    const detections = result.textAnnotations;
    return detections.map(text => text.description);
  } catch (error) {
    console.error('Error during text detection:', error);
    if (error.code === 7) {
      console.error('API quota exceeded');
    }
    throw error;
  }
}

// Example usage
extractTextFromImage('images/sample.jpg')
  .then(text => console.log('Extracted text:', text))
  .catch(error => console.error('Error:', error));

```

<span aria-hidden="true" id="processing-pdf-files"></span>

## Processing PDF files

To extract text from PDFs, use the asynchronous batch annotation feature with Google Cloud Storage:

```javascript
async function extractTextFromPDF(gcsSourceUri, gcsDestinationUri) {
  const client = new vision.ImageAnnotatorClient();

  const inputConfig = {
    mimeType: 'application/pdf',
    gcsSource: {
      uri: gcsSourceUri
    }
  };

  const outputConfig = {
    gcsDestination: {
      uri: gcsDestinationUri
    },
    batchSize: 1
  };

  const features = [{ type: 'DOCUMENT_TEXT_DETECTION' }];
  const request = {
    requests: [{
      inputConfig,
      features,
      outputConfig,
    }]
  };

  const [operation] = await client.asyncBatchAnnotateFiles(request);
  const [filesResponse] = await operation.promise();

  return filesResponse;
}

```

<span aria-hidden="true" id="api-limitations-and-pricing"></span>

## API limitations and pricing

* Free tier: 1,000 units per month
* PDF processing limit: 2,000 pages per file
* API pricing: $1.50 per 1,000 units after free tier
* PDF processing: 5 pages = 1 unit

<span aria-hidden="true" id="regional-configuration"></span>

## Regional configuration

For data residency requirements, you can specify regional endpoints:

```javascript
const client = new vision.ImageAnnotatorClient({
  apiEndpoint: 'eu-vision.googleapis.com', // European Union
  // or 'us-vision.googleapis.com' // United States
})

```

<span aria-hidden="true" id="troubleshooting"></span>

## Troubleshooting

<span aria-hidden="true" id="common-issues-and-solutions"></span>

### Common issues and solutions

1. Authentication Errors
   * Verify the service account key file path
   * Ensure the service account has proper permissions
   * Check if the API is enabled in your project
2. PDF Processing Issues
   * Confirm the PDF file is under 2,000 pages
   * Verify GCS bucket permissions
   * Check PDF file format compatibility
3. Rate Limiting
   * Implement exponential backoff for retries
   * Monitor quota usage in the GCP Console
   * Consider batch processing for large volumes

<span aria-hidden="true" id="best-practices"></span>

## Best practices

1. Error Handling

```javascript
async function processDocument(filePath) {  
  try {  
    const result = await extractTextFromImage(filePath);  
    return result;  
  } catch (error) {  
    if (error.code === 'ENOENT') {  
      throw new Error('File not found');  
    }  
    if (error.code === 7) {  
      throw new Error('API quota exceeded');  
    }  
    throw error;  
  }  
}  
```

2. Batch Processing

```javascript
async function processBatch(files, concurrency = 3) {  
  const results = [];  
  for (let i = 0; i < files.length; i += concurrency) {  
    const batch = files.slice(i, i + concurrency);  
    const batchResults = await Promise.all(  
      batch.map(file => processDocument(file).catch(error => ({ error })))  
    );  
    results.push(...batchResults);  
    await new Promise(resolve => setTimeout(resolve, 1000)); // Rate limiting  
  }  
  return results;  
}  
```

<span aria-hidden="true" id="conclusion"></span>

## Conclusion

Integrating GCP OCR into your Node.js applications enables powerful OCR capabilities. By automating text extraction from images and PDFs, you can enhance your application's functionality, streamline workflows, and provide more value to your users.

Transloadit also offers a [Document OCR](/docs/robots/document-ocr.md) robot as part of our[Artificial Intelligence service](/services/artificial-intelligence.md) for seamless and scalable OCR processing.

\#gcp-ocr#google-cloud-vision-api#node-js#text-extraction#document-processing#artificial-intelligence-service

### 👩‍💻 Join 20k+ developers

Sign up for our [monthly newsletter](/newsletters.md) to receive direct links to 3 exclusive tech — and 2 product updates. No less, no more.

Your email:

Get access

## File uploading and encoding. Made simple.

Transloadit streamlines file handling for developers, trusted by brands like Coursera and The New York Times. We’re known for a reliable API, top-notch support, and a strong commitment to open source, with projects like [Uppy⁠](https://uppy.io) and [Tus⁠](https://tus.io) setting standards in file processing.

[Sign up](/c/)[Book a Demo](https://survey.typeform.com/to/kRg47Xi5)

No credit card needed

Cancel anytime
