Java SDK user guide

Updated at:

Use the Alibaba Cloud Java SDK to call Document Mind parsing APIs and extract hierarchical structures, text content, key-value fields, and style information from documents. This guide covers the SubmitDocStructureJobAdvance API (local file upload), the SubmitDocStructureJob API (URL upload), and the GetDocStructureResult API (result query).

Review the OpenAPI documentation

Before calling an API, review the API reference for required parameters and permissions.

Prerequisites

Before calling a Document Mind API with the Java SDK, complete the following tasks.

Set up the Java SDK environment

  1. Make sure that Java 8 or later is installed on your machine.

  2. Add the following dependencies to the pom.xml file of your Maven project: the Alibaba Cloud SDK core library tea-openapi and the Document Mind SDK docmind_api20220711.

    <dependencies>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>tea-openapi</artifactId>
            <version>0.3.12</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>docmind_api20220711</artifactId>
            <version>2.0.14</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.50</version>
        </dependency>
    </dependencies> 

Configure authentication

  1. Create an AccessKey pair. For more information, see Create an access key pair.

  2. Create a RAM user and grant it the minimum permissions required. RAM lets multiple users in your organization access cloud resources independently, so you don't need to share the AccessKey of your Alibaba Cloud account (root). Alibaba Cloud provides preset permission policies for common scenarios. You can also create and configure permissions manually. For more information, see Quick start: Create a RAM user and grant permissions.

    Important
    • An Alibaba Cloud account (root) has Administrator permissions on all cloud resources under the account by default, and these permissions cannot be modified. If the AccessKey of your Alibaba Cloud account (root) is leaked, all resources under the account are at risk. To keep your account secure, we strongly recommend that you do not create an AccessKey for your Alibaba Cloud account (root). Instead, create a RAM user dedicated to API access, create an AccessKey for the RAM user, grant least privilege permissions, and then use the RAM user to access Alibaba Cloud resources programmatically.

    • Do not embed your AccessKey ID or AccessKey Secret in project source code. This can expose your credentials. For more security best practices on credentials, see Credential security solutions.

  3. Add the Alibaba Cloud SDK Credentials dependency:

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>credentials-java</artifactId>
        <version>1.0.3</version>
    </dependency>
  4. Configure authentication using a credentials file. Create ~/.alibabacloud/credentials.ini and add your AccessKey credentials. For more information, see Manage access credentials in the SDK for Java.

    [default]
    enable = true
    type = access_key
    access_key_id = <your-access-key-id>
    access_key_secret = <your-access-key-secret>

Call the OpenAPI

Document Mind parsing APIs use an asynchronous pattern: submit a document using SubmitDocStructureJobAdvance (local file) or SubmitDocStructureJob (URL), then poll for results using GetDocStructureResult.

Note
  • Poll every 10 seconds for up to 120 minutes. If no result is returned within 120 minutes, the task has timed out.

  • After an asynchronous task is completed, you can query the results within 24 hours. Results are not available after 24 hours.

  • The image-to-Word, image-to-Excel, and image-to-PDF APIs do not support file upload.

Submit a document processing task

Two upload methods are supported:

  • Local file upload: Use the SubmitDocStructureJobAdvance API.

  • URL upload: Use the SubmitDocStructureJob API.

For large files with long processing times, set the following properties of the config object:

// Connection timeout in milliseconds
config.connectTimeout = 60000;
// Read timeout in milliseconds
config.readTimeout = 60000;

Submit an asynchronous task with a local file

The following example calls the SubmitDocStructureJobAdvance API to submit an asynchronous task with a local file.

import com.aliyun.docmind_api20220711.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.docmind_api20220711.Client;
import com.aliyun.teautil.models.RuntimeOptions;
import com.alibaba.fastjson.JSON;
import java.io.File;
import java.io.FileInputStream;

public class SubmitLocalFileDemo {
    public static void main(String[] args) throws Exception {
        submit();
    }

    public static void submit() throws Exception {
        // Reads AccessKey from ~/.alibabacloud/credentials.ini for authentication.
        // Before running, complete the authentication setup in Prerequisites.
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
        Config config = new Config()
            .setAccessKeyId(credentialClient.getAccessKeyId())
            .setAccessKeySecret(credentialClient.getAccessKeySecret());
        // Endpoint. For IPv6, use docmind-api-dualstack.cn-hangzhou.aliyuncs.com.
        config.endpoint = "docmind-api.cn-hangzhou.aliyuncs.com";
        Client client = new Client(config);
        RuntimeOptions runtime = new RuntimeOptions();
        SubmitDocStructureJobAdvanceRequest advanceRequest = new SubmitDocStructureJobAdvanceRequest();
        // Replace with the actual local file path.
        File file = new File("D:\\example.pdf");
        advanceRequest.fileUrlObject = new FileInputStream(file);
        advanceRequest.fileName = "example.pdf";
        SubmitDocStructureJobResponse response = client.submitDocStructureJobAdvance(advanceRequest, runtime);
        System.out.println(JSON.toJSON(response.getBody()));
    }
}

Response

{
  "RequestId": "4FF7D611-782B-1557-AF71-6541E10A****",
  "Data": {
    "Id": "docmind-20220902-824b****"
  }
}

Submit an asynchronous task with a document URL

The document URL must be publicly accessible, free of cross-origin restrictions, and free of special escape characters. The following example calls the SubmitDocStructureJob API to submit an asynchronous task with a document URL.

import com.aliyun.docmind_api20220711.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.docmind_api20220711.Client;
import com.alibaba.fastjson.JSON;

public class SubmitUrlFileDemo {
    public static void main(String[] args) throws Exception {
        submit();
    }

    public static void submit() throws Exception {
        // Reads AccessKey from ~/.alibabacloud/credentials.ini for authentication.
        // Before running, complete the authentication setup in Prerequisites.
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
        Config config = new Config()
            .setAccessKeyId(credentialClient.getAccessKeyId())
            .setAccessKeySecret(credentialClient.getAccessKeySecret());
        // Endpoint. For IPv6, use docmind-api-dualstack.cn-hangzhou.aliyuncs.com.
        config.endpoint = "docmind-api.cn-hangzhou.aliyuncs.com";
        Client client = new Client(config);
        SubmitDocStructureJobRequest request = new SubmitDocStructureJobRequest();
        request.fileName = "example.pdf";
        // Replace with an actual publicly accessible document URL.
        request.fileUrl = "https://example.com/example.pdf";
        SubmitDocStructureJobResponse response = client.submitDocStructureJob(request);
        System.out.println(JSON.toJSON(response.getBody()));
    }
}

Response

{
  "RequestId": "4FF7D611-782B-1557-AF71-6541E10A****",
  "Data": {
    "Id": "docmind-20220902-824b****"
  }
}

Query task results

The following example queries results using the GetDocStructureResultRequest API. The response returns one of three statuses: processing, succeeded, or failed.

import com.aliyun.docmind_api20220711.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.docmind_api20220711.Client;
import com.alibaba.fastjson.JSON;

public class GetDocStructureResultDemo {
    public static void main(String[] args) throws Exception {
        query();
    }

    public static void query() throws Exception {
        // Reads AccessKey from ~/.alibabacloud/credentials.ini for authentication.
        // Before running, complete the authentication setup in Prerequisites.
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
        Config config = new Config()
            .setAccessKeyId(credentialClient.getAccessKeyId())
            .setAccessKeySecret(credentialClient.getAccessKeySecret());
        // Endpoint. For IPv6, use docmind-api-dualstack.cn-hangzhou.aliyuncs.com.
        config.endpoint = "docmind-api.cn-hangzhou.aliyuncs.com";
        Client client = new Client(config);
        GetDocStructureResultRequest resultRequest = new GetDocStructureResultRequest();
        // Replace with the task ID returned by the submission API.
        resultRequest.id = "docmind-20220902-824b****";
        GetDocStructureResultResponse response = client.getDocStructureResult(resultRequest);
        System.out.println(JSON.toJSON(response.getBody()));
    }
}

Response

  • Processing: When Completed is false, the task is still in progress. Continue polling until Completed returns true or the maximum polling time is exceeded.

    {
      "RequestId": "2AABD2C2-D24F-12F7-875D-683A27C3****",
      "Completed": false,
      "Code": "DocProcessing",
      "Message": "Document processing",
      "HostId": "ocr-api.cn-hangzhou.aliyuncs.com",
      "Recommend": "https://next.api.aliyun.com/troubleshoot?q=DocProcessing&product=docmind-api"
    }
  • Succeeded: When Completed is true and Status is Success, the task has completed successfully. The parsed results are in the Data node.

    {
      "Status": "Success",
      "RequestId": "73134E1A-E281-1B2C-A105-D0ECFE2DFail",
      "Completed": true,
    	"Data": {
    		"styles": [{
    				"styleId": 0,
    				"underline": false,
    				"deleteLine": false,
    				"bold": true,
    				"italic": false,
    				"fontSize": 15,
    				"fontName": "SimHei",
    				"color": "000000",
    				"charScale": 0.95
    			},
    			{
    				"styleId": 1,
    				"underline": false,
    				"deleteLine": false,
    				"bold": false,
    				"italic": false,
    				"fontSize": 12,
    				"fontName": "Microsoft YaHei",
    				"color": "000000",
    				"charScale": 1
    			}
    		],
    		"layouts": [{
    			"text": "Sample title",
    			"index": 0,
    			"uniqueId": "xxxx9816e77caea338df554b80ab95c7",
    			"alignment": "center",
    			"pageNum": [
    				0
    			],
    			"pos": [{
    					"x": 405,
    					"y": 192
    				},
    				{
    					"x": 860,
    					"y": 191
    				},
    				{
    					"x": 860,
    					"y": 236
    				},
    				{
    					"x": 406,
    					"y": 237
    				}
    			],
    			"type": "title",
          "subType":"doc_title"
    		}, {
    			"text": "This is sample content",
    			"index": 1,
    			"uniqueId": "xxxx8606c213c01c12d70f98dcfb2525",
    			"alignment": "left",
    			"pageNum": [
    				0
    			],
    			"pos": [{
    					"x": 187,
    					"y": 311
    				},
    				{
    					"x": 1075,
    					"y": 311
    				},
    				{
    					"x": 1076,
    					"y": 373
    				},
    				{
    					"x": 187,
    					"y": 373
    				}
    			],
    			"type": "text",
          "subType":"para",
    			"lineHeight": 7,
    			"firstLinesChars": 30,
    			"blocks": [{
    					"text": "This is",
    					"pos": null,
    					"styleId": 0
    				},
    				{
    					"text": "sample content",
    					"pos": null,
    					"styleId": 1
    				}
    			]
    		}],
    		"logics": {
    			"docTree": [{
    				"uniqueId": "xxxx9816e77caea338df554b80ab95c7",
    				"level": 0,
    				"link": {
    					"Children": [
    
    					],
    					"Contains": [
    
    					]
    				},
    				"backlink": {
    					"Parent": [
    						"ROOT"
    					]
    				}
    			}],
    			"paragraphKVs": null,
    			"tableKVs": null
    		},
    		"docInfo": {
    			"docType": "pdf",
    			"orignalDocName": "1.pdf",
    			"pages": [{
    				"imageType": "JPEG",
    				"imageUrl": "http://test.moshi.aliyuncs.com/docMind/image/xxxx3cccbfec45b48d3a8081c9c9659e/0",
    				"angle": null,
    				"imageWidth": 1273,
    				"imageHeight": 1801,
    				"pageIdCurDoc": 1,
    				"pageIdAllDocs": 1
    			}]
    		}
    	}
    }
  • Failed: When Completed is true and Status is Fail, the task failed. Check Code for the error code and Message for details. For a full list of error codes, see Error codes.

    {
      "RequestId": "A8EF3A36-1380-1116-A39E-B377BE27****",
      "Completed": true,
      "Status": "Fail",
      "Code": "UrlNotLegal",
      "Message": "Failed to process the document.  The document url you provided is not legal.",
      "HostId": "docmind-api.cn-hangzhou.aliyuncs.com",
      "Recommend": "https://next.api.aliyun.com/troubleshoot?q=IDP.UrlNotLegal&product=docmind-api"
    }