You are here: Home - OCR Cloud 2.0 API - Code Samples

Code Samples

OCR Cloud 2.0 API Code Samples

PHP Code Sample



// 1. First, we need to build an XML string to send

// to the API. In the example below, the sring is

// built in a very straight forward way.



// Lets start with adding to our string input URL and file type, which is

// the file you want to process

$filename = ‘’;

$inputURL = ‘<InputURL>’ . $filename . ‘</InputURL>’;

$inputTYPE = ‘<InputType>TIF</InputType>’;


// If you want to build a page to where the result would

// be proccessed, you need to specify the Notify URL

// Uncomment the next line if you want to use the feature

// and dont forget to add it to a job string down below

//$notifyURL = ‘<NotifyURL></NotifyURL>’;


//(Optional)Next step is to add cleanup options.

$cleanup = ‘<CleanupSettings>’;

$cleanup .=’<Deskew>false</Deskew>’;



$cleanup .=’<RotationType>Automatic</RotationType>’;

$cleanup .=’</CleanupSettings>’;


// (Optional)After clean up options, we are going to indicate

// OCR setting for your file


$settings.=’<PrintType>Print;Typewriter</PrintType>’; //I have indicated multiple print types separated by ‘;’

$settings.=’<OCRLanguage>English;Danish</OCRLanguage>’; //and again, multiple items separated by ‘;’\






// (Optional) You can also specify a format is which you want to receive

// you processed file in





// Now create a job with all the settings you have specified

$job = ‘<Job>’ . $inputURL . $inputTYPE . $cleanup . $settings . $output .’</Job>’;




// 2. Now that we have made our upload string with all

// the settings we desire, we are going to create an

// xml request using curl.



// First, we are going to define POST URL

$key = ‘your_key_here’;

define(‘XML_REQUEST’, $job); //this is the actual request to be sent

define(‘XML_POST_URL’, ‘’ . $key ); //this is where we want it to be sent


// Then we will initialize handle and set request options

$header[] = ‘Content-type: text/xml’;

$header[] = ‘Connection: close’;


// Now, we will use defined settings above to create an xml

// request using curl

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, XML_POST_URL);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_TIMEOUT, 4);


curl_setopt($ch, CURLOPT_HTTPHEADER, $header);


// After we have created the request we will

// execute it (Optional) and also time the transaction

$start = array_sum(explode(‘ ‘, microtime()));

$result = curl_exec($ch); //executes our xml request

$stop = array_sum(explode(‘ ‘, microtime()));

$totalTime = $stop – $start;


// It is always a good practice to check for errors

// In my case, i just output them for visual review/debugging

if ( curl_errno($ch) )


$result = ‘ERROR -> ‘ . curl_errno($ch) . ‘: ‘ . curl_error($ch);




$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); //checks for url errors


case 404:

$result = ‘ERROR -> 404 Not Found’;







// Once the execution is done close the handle



// (Optional) Output the results and time

echo ‘</br>’;

echo ‘Total time for request: ‘ . $totalTime . “\n”;

echo “Submit Result” .$result;




// 3. After we have sucessfuly sent the request over to

// the API, we need to receive a result. Usually, result

// is available several seconds later, se we would need

// to query the API with received job ID. Or, you can

// build a webpage that will alert you once the links

// to the new generated files are ready.



//Let’s start by reading the xml we received as a result

// of executing curl xml request

$dom = new DOMDocument;


$xml = simplexml_import_dom($dom); // we are using simplexml here

$jobURL = $xml->JobURL; // a job URL has been obtained


// Now that we have URL for our pending job,

// we will querry it untill we recieve a status

// indicating that the job is done.


$status =2;

while($status>0){ //status = 0, means we are done.

$reader =  new XMLReader();  //we are using XMLReader function


while($reader->read()){ // if we have more than one URI, this while will take care of it.

if($reader->nodeType == XMLReader::ELEMENT && $reader->name == ‘Status’){ //find status xml element

$reader->read(); // go to its value

if($reader->value==’Finished’){ //if the status is finished, we will read one more time to receive URI(s)

$status= $status -1; // indicates that we are ready to read URI, since the job is finished



if($reader->nodeType == XMLReader::ELEMENT && $reader->name == ‘Uri’ && $status==1){ //This is where the link to the new file(s) is located


$url[$i] =  $reader->value; // we are creating array, if necessary, for storing URI




sleep(3); // wait 3 seconds before doing another querry


$reader->close(); // close the xml reader

// (Optional) Output the URI of files you have requested

// If you requested more or less filetypes, change output accordingly

echo ‘<br/> JobTXT: ‘ . $url[0];

echo ‘<br/> JobPDF: ‘ . $url[1];



POST Sample

URL Example:

HTTP POST to{your_key}

Message body example (minimum):

<InputURL> </InputURL>

Message body example (enhanced):


Message body example (full):


Response example:



.NET C# Code Sample

using System;

using System.Collections.Generic;

using System.Linq;

using System.Xml.Linq;

using System.Text;

using System.Net;

using System.Threading;


namespace OCRSampleClient


class Program


static void Main(string[] args)


string imageUrl = “”;

string key = “your_key_here”;


XElement xe = new XElement(“Job”,

new XElement(“InputURL”, imageUrl)



WebClient wc = new WebClient();

wc.Headers[HttpRequestHeader.ContentType] = “text/xml”;

ServicePointManager.Expect100Continue = false;


string results = wc.UploadString(

“” + key,





string textURL = null;


//Use “dumb polling” every 2 seconds in this simplified example, until done.

//In a real application, notification with NotifyURL should be used instead.

while (true)


XElement resultsXml = XElement.Parse(results);

string jobURL = resultsXml.Element(“JobURL”).Value;

string status = resultsXml.Element(“Status”).Value;


if (status == “Finished”)


textURL = (

from elem in resultsXml.Element(“Download”).Elements(“File”)

where elem.Element(“OutputType”).Value == “TXT”

select elem.Element(“Uri”).Value





//Exit if there’s an error

if ((status != “Submitted”) && (status != “Processing”)) break;


Thread.Sleep(2000); // 2 seconds

results = wc.DownloadString(jobURL);



if (textURL == null)


Console.WriteLine(“An error has occurred”);




string text = wc.DownloadString(textURL);



Console.WriteLine(“PRESS ENTER TO EXIT”);






Android OS Demo App + Complete Source Code Sample

OCR-IT Demo Android App is a complete simple implementation of OCR Cloud 2.0 API on Android OS.  Designed to showcase the entire image to text process on a mobile phone, this App can be used for quick testing and development purposes.

Android App (APK file):

Complete Source Code:


OCR-IT OCR Cloud API Android Demo App Screen 1

Screen 1: Developer credentials, Image source

OCR-IT OCR Cloud API Android Demo App Screen 2

Screen 2: Review of image, Select OCR language

OCR-IT OCR Cloud API Android Demo App Screen 3

Screen 3: Processing

OCR-IT OCR Cloud API Android Demo App Screen 4

Screen 4: Text in TXT and PDF

OCR-IT OCR Cloud API Android Demo App Screen 5

Screen 5: TXT view

Python Code Sample

Use WiseTREND OCR cloud from Python.
import wisetrend
import time
joburl = wisetrend.submit("API-KEY", "http://url/to/the/document")
while True:
status, downloads = wisetrend.getstatus(joburl)
print status
if status == "Finished":
for outputtype, url in downloads.iteritems():
print outputtype, url
Copyright (c) 2011 Bernt R. Brenna
Licensed under the MIT license:
import urllib2
from xml.etree import ElementTree as E
class SubmitError(Exception):
URL = ""
def submit(key, inputurl):
    """Returns the job url"""
    job_element = E.Element("Job")
    E.SubElement(job_element, "InputURL").text = inputurl
    request = urllib2.Request(URL + key, data=E.tostring(job_element), headers={
        "Content-Type": "text/xml"
        response = urllib2.urlopen(request)
    except urllib2.HTTPError as e:
        raise SubmitError(
        jobstatus = E.fromstring(
        if jobstatus.find("Status").text == "Submitted":
            return jobstatus.find("JobURL").text
            raise SubmitError(E.tostring(jobstatus))
def getstatus(joburl):
    """Returns a tuple (Status, {"OutputType": downloaduri})
If the status is not Finished, returns (Status, {})
    jobstatus = E.fromstring(urllib2.urlopen(joburl).read())
    if jobstatus.find("Status").text == "Finished":
        return "Finished", dict((file_element.find("OutputType").text, file_element.find("Uri").text)
                                for file_element in jobstatus.findall("Download/File"))
        return jobstatus.find("Status").text, {}
if __name__ == "__main__":
    from optparse import OptionParser
    parser = OptionParser(usage="\n1. %prog submit --key secretkey --inputurl inputurl\n2. %prog getstatus --joburl joburl")
    opts, args = parser.parse_args()
    if len(args) != 1:
        parser.error("Specify submit or getstatus")
    if args[0] == "submit":
        joburl = submit(opts.key, opts.inputurl)
        print "Job URL:", joburl
    if args[0] == "getstatus":
        status, downloads = getstatus(opts.joburl)
        print "Status:", status
        for outputtype, url in downloads.iteritems():
            print outputtype, url


Java Code Sample

// *******************************************************

//       Contributor: Vinothkumar Arputharaj

//       Contact:

// *******************************************************

import org.apache.http.HttpHost;

import org.apache.http.HttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.params.ClientPNames;

import org.apache.http.client.params.CookiePolicy;

import org.apache.http.conn.params.ConnRoutePNames;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.params.BasicHttpParams;

import org.apache.http.params.HttpConnectionParams;

import org.apache.http.params.HttpParams;

import org.apache.http.util.EntityUtils;



public class OCRRestClient {


private static int proxyPort = 80;                  // Assign your Proxy Port here

private static String proxyHost=””;  // Assign your Proxy Host here



public static void main(String[] args) {


HttpParams myParams = new BasicHttpParams();// variable to add additional parameters to the httpClient


// The next two lines are necessary to avoid “Connection Timeout” Exception

HttpConnectionParams.setConnectionTimeout(myParams, 10000);

HttpConnectionParams.setSoTimeout(myParams, 10000);


// Create a client object

DefaultHttpClient httpClient = new DefaultHttpClient(myParams);


HttpHost proxy = new HttpHost(proxyHost, proxyPort);                                                                     // For connections that need proxy


httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);// Set proxy to the http client


try {

String ret = null;        // Actual response as string


String key = “your key”;  // Enter your secret key obtained from WiseTrend


// Image URL. This needs to be a “http” / “https” url.

String imageURL = ””;


HttpResponse response  = null;    // Response object


HttpPost httppost = new HttpPost(“”+key);


// Set the content type of the request



// Set the request parameter as Entity. See the documentation for detailed request entity.

httppost.setEntity(new StringEntity(“<Job>” +




// Execute the post request

response = httpClient.execute(httppost );


System.out.println(response.toString()); // Printing the response


if (response != null) {

ret = EntityUtils.toString(response.getEntity());


System.out.println(“Response: “+ret); // Printing the response Entity


// Create staXParser object to pare the response string (which is in xml format)

StaXParser stp = new StaXParser();


stp.readXMLStream(ret.toString());         // Parse the response string


System.out.println(“Final status : “+StaXParser.STATUS); // Printing the status




// Send GET request to get the URI of the output file

HttpGet httpget = new HttpGet(StaXParser.JOBURL);


System.out.println(“Sending GET Request”);



HttpResponse response1 = httpClient.execute(httpget);


if(response1 != null)


ret = EntityUtils.toString(response1.getEntity());


System.out.println(“RES 1 : “+ret);

// Printing response for GET request


StaXParser stp1 = new StaXParser();


// Parse the response from GET request


System.out.println(“GET Job status : “+StaXParser.STATUS);                                                                    //Printing Job Status


// Rest of the code is self explanatory



String tempFileURI = null;


for(int p=0; p<StaXParser.URIARRAY.length; p++)


if(StaXParser.FILETYPEARRAY[p] != null && StaXParser.FILETYPEARRAY[p].equalsIgnoreCase(“TXT”))



// Printing the output “Txt” file path & type

tempFileURI = StaXParser.URIARRAY[p];













}catch(Exception e){