DEV Community

Pratham 👨‍💻✨ for RapidAPI

Posted on

Build an Image-to-Text Extractor Application using API

Text extraction is a process in which we extract ASCII characters from the image or a scanned document. This kind of application has a wide range of scope, including text recognition which further helps in various Machine Learning algorithms.

In this article, we will build a simple yet powerful Text Extraction application using Pen to Print - Handwriting OCR API and React.

How to connect to the Facial Text Analysis API

RapidAPI handles all the API development things very effectively. You don't need to worry about any complicated stuff related to APIs like rate-limiting factors, authentication, and authorization. You just need to register on RapidAPI Hub if you want to use any API. RapidAPI provides you a single API key using which you can access over 35,000 APIs conveniently.

Go to RapidAPI Hub and create a free account.

sign up page of RapidAPI Hub

The majority of the APIs offer a freemium plan. You don't even need to add credit card details to access them. Let's choose the best-suited pricing plan for Pen to Print - Handwriting OCR.

The Basic plan of Pen to Print - Handwriting OCR is free but keep in mind that it only offers 100 API calls per month. You can always change the plan according to your needs. Just click on the "Subscribe" button of the Basic plan.

Now we are good to create a Text Extraction App using this API.

pricing page of Pen to Print = Handwriting OCR API

Play around with Pen to Print - Handwriting OCR API

Once you subscribe, you can test the API and check the response this Pen to Print - Handwriting OCR API returns. You can test multiple endpoints with different parameters using the API playground. Let's try to dig in with our current API to integrate it with our application.

homepage of pen to print - handwriting OCR

  1. Endpoints
    Here, you can take a quick look at the endpoints an interface supports. You can also search for a distinct endpoint.

  2. Documentation
    Here, you can access and change all the necessary details required to test an endpoint. For example, you can pass values in the different parameters in the documentation section.

  3. Code
    Every developer wants and loves this section. You can copy-paste the code directly from here. RapidAPI supports 20 programming languages with 40 different libraries.

The Pen to Print - Handwriting OCR has only one endpoint which lets us make a POST request after uploading the image file from local storage.

Scroll down a little bit in the documentation section. You will find a Request Body section, here you can pass all the necessary parameters. Upload an image from your device to test this API.

Great, we are all set to hit the "Test Endpoint" button.

![test pen to print image

After clicking the "Test Endpoint" button, you will see the endpoint (API) result in the third section of the API Playground.

response of pen to print - Handwriting OCR

In the response body (returned data from the server) you will get a value key that contains all the text present in the image.

Integrate Pen to Print - Handwriting OCR API into Your React Application

React is a front-end JavaScript library for building user interfaces. In this article, you will learn how to integrate an API into your React application and build a text extraction application. Just follow the steps below:

1. Create a React Application

Create React App is the simplest way to set up a React application by running one command.

npx create-react-app image-to-text 
Enter fullscreen mode Exit fullscreen mode

You will need to have Node.js (version >= 6) on your local machine. If you haven't, just download it for free.

Create-react-app command will create a folder for you with all the necessary files and folders required for a React application. You will get a node_modules, public and src folder.

file structure of React app

2. Create a Form

We want a form in our application where users can upload the image in order to extract text. We just need a file input field and a submit button in the form.

Go to your project folder (image-to-text that we just created in the first step) and you'll find that React created a bunch of other folders and files for us. We don't need to check them all right now.

Go to the image-to-text folder > src > App.js file and create a form with a file input field and a submit button.

function App() {
  return (
    <div>
      <h1>Image to Text Extractor</h1>
      <form>
        <input type="file" />
        <input type="submit" value="Extract Text" />
      </form>
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Run the application to check the output by running the following command from the root of the project and go to https://localhost:3000:

npm start
Enter fullscreen mode Exit fullscreen mode

text extractor application

3. Copy-paste the code snippet from RapidAPI Hub

We are all set to integrate Text Analysis API code into our application. You don't even need to write the code. RapidAPI provides the code snippet in 20 programming languages with 40 libraries' support.

Go to the Pen to Print - Handwriting OCR API homepage and copy the code snippet from the Copy Snippets section of the API playground.

Select the JavaScript language and axios method from the dropdown menu and click on the "Copy Code" button.

copy code snippet of Pen to Print - Handwriting OCR API

Create a handleFormSubmit() function in the App.js file and paste the code inside that function.

We need to install the axios library first in order to use it in our application. Run the following command from the root of the project.

npm install axios 
Enter fullscreen mode Exit fullscreen mode

4. Let the user upload the image and extract the text

We are almost done! We just need to validate the form so that the user can enter the text to get the result.

Let's complete the form first. Create two useState hooks in the App.js file, one for handling the state binary image file to make the API call, and the second is for displaying the image that user uploads.

const [previewImage, setPreviewImage] = useState("");
const [imageFile, setImageFile] = useState({});

<form onSubmit={handleFormSubmit}>
  <input type="file" onChange={handleFileInputChange} />
  <input type="submit" value="Extract Text" />
</form>
Enter fullscreen mode Exit fullscreen mode

Call a function handleFileInputChage whenever a user uploads the new image file. Inside that function, we need to set the states so that we can display the preview image and convert the image file to binary in order to make the API call.

function handleFileInputChange(event) {
  setImageFile(event.target.files[0]);
  setPreviewImage(URL.createObjectURL(event.target.files[0]));
}
Enter fullscreen mode Exit fullscreen mode

As simple as that, we are setting the binary format inside imageFile and object URL inside previewImage using URL.createObjectURL method.

Let's create another useState hook for storing the response that the server returns.

const [text, setText] = useState("");
Enter fullscreen mode Exit fullscreen mode

Modify the handleFormSubmit function a little bit to store the text response string.

axios
  .request(options)
  .then(function (response) {
    setText(response.data.value);
  })
  .catch(function (error) {
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

Render the extracted text on the webpage when the API successfully returns the data. You can do this by adding some paragraph tags inside the return method in the App.js file.

If you missed some parts, this is how the entire App.js file looks like.

import axios from "axios";
import { useState } from "react";
function App() {
  const [previewImage, setPreviewImage] = useState("");
  const [imageFile, setImageFile] = useState({});
  const [text, setText] = useState("");
  function handleFileInputChange(event) {
    setImageFile(event.target.files[0]);
    setPreviewImage(URL.createObjectURL(event.target.files[0]));
  }
  function handleFormSubmit(event) {
    event.preventDefault();
    const form = new FormData();
    form.append("Session", "string");
    form.append("srcImg", imageFile);
    const options = {
      method: "POST",
      url: "https://pen-to-print-handwriting-ocr.p.rapidapi.com/recognize/",
      headers: {
        "content-type": "multipart/form-data",
        "x-rapidapi-host": "pen-to-print-handwriting-ocr.p.rapidapi.com",
        "x-rapidapi-key": process.env.REACT_APP_API_KEY,
      },
      data: form,
    };
    axios
      .request(options)
      .then(function (response) {
        setText(response.data.value);
      })
     .catch(function (error) {
       console.error(error);
     });
   }
  return (
    <div className="App">
      <h1>Image to Text Extractor</h1>
      <img src={previewImage} />
        <form onSubmit={handleFormSubmit}>
          <input type="file" onChange={handleFileInputChange} />
          <input type="submit" value="Extract Text" />
       </form>
       <p className="text">{text}</p>
     </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

One important thing to note here is that we have passed the API key as

"x-rapidapi-key": process.env.REACT_APP_API_KEY,
Enter fullscreen mode Exit fullscreen mode

x-rapidapi-key is your API key that RapidAPI provides using which you can access over 35,000 excellent APIs. It's always recommended to pass the API key as an environment variable because it's a confidential thing. Anyone can use your API subscription if they have your API key.

Create a .env inside the image-to-text folder and add your API key inside REACT_APP_API_KEY(you can call it whatever you want but it should start with the prefix REACT_APP_ ) variable. Now you can access it inside the App.js file as process.env.REACT_APP_API_KEY.

5. Output

Yay! Run the npm start command, and you'll see the result at http://localhost:3000/.

image to text extractor application

You can check the working project here.

You can add styling using CSS to make it look more appealing.

final result of text extractor application

Go to RapidAPI Hub and create a free account to get your API key. The fun part is that you can use over 35,000 excellent APIs with just one API key. So it's worth creating a free account on RapidAPI Hub.

Feel free to drop your suggestions, feedback, and doubts down below. We love checking them out.

With that said, we hope you enjoy this article. Peace out!! Keep coding! We will catch you with the next excellent project idea.

Top comments (0)