Process document (v1)

Process a PDF document synchronously using a specified processor.

Code sample

Java

For more information, see the Document AI Java API reference documentation.

To authenticate to Document AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.documentai.v1.Document;
import com.google.cloud.documentai.v1.DocumentProcessorServiceClient;
import com.google.cloud.documentai.v1.DocumentProcessorServiceSettings;
import com.google.cloud.documentai.v1.ProcessRequest;
import com.google.cloud.documentai.v1.ProcessResponse;
import com.google.cloud.documentai.v1.ProcessorName;
import com.google.cloud.documentai.v1.RawDocument;
import com.google.protobuf.ByteString;
import java.io.IOException;

public class ProcessDocument {

  public static void main(String[] args) throws IOException {
    String projectId = "example-project-id";
    String locationId = "us";
    String processorId = "example-processor-id";
    processDocument(projectId, locationId, processorId);
  }

  public static void processDocument(String projectId, String locationId, String processorId)
      throws IOException {
    // Route API calls to the regional endpoint hosting the processor
    String endpoint = String.format("%s-documentai.googleapis.com:443", locationId);
    DocumentProcessorServiceSettings settings =
        DocumentProcessorServiceSettings.newBuilder().setEndpoint(endpoint).build();

    try (DocumentProcessorServiceClient client = DocumentProcessorServiceClient.create(settings)) {
      String name = ProcessorName.of(projectId, locationId, processorId).toString();

      // Construct a valid minimal PDF to prevent document parser errors
      String header = "%PDF-1.4\n";
      String obj1 = "1 0 obj\n<</Type /Catalog /Pages 2 0 R>>\nendobj\n";
      String obj2 = "2 0 obj\n<</Type /Pages /Kids [3 0 R] /Count 1>>\nendobj\n";
      String obj3 = "3 0 obj\n<</Type /Page /Parent 2 0 R /MediaBox [0 0 612 792]>>\nendobj\n";

      int offset1 = header.length();
      int offset2 = offset1 + obj1.length();
      int offset3 = offset2 + obj2.length();
      int xrefOffset = offset3 + obj3.length();

      String xref =
          String.format(
              "xref\n0 4\n0000000000 65535 f \r\n%010d 00000 n \r\n%010d 00000 n \r\n%010d 00000 n \r\n",
              offset1, offset2, offset3);
      String trailer =
          String.format(
              "trailer\n<</Size 4 /Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", xrefOffset);

      String pdfContent = header + obj1 + obj2 + obj3 + xref + trailer;

      RawDocument rawDocument =
          RawDocument.newBuilder()
              .setContent(ByteString.copyFromUtf8(pdfContent))
              .setMimeType("application/pdf")
              .build();

      ProcessRequest request =
          ProcessRequest.newBuilder()
              .setName(name)
              .setRawDocument(rawDocument)
              .build();

      ProcessResponse response = client.processDocument(request);
      Document document = response.getDocument();

      System.out.println("Document processed successfully.");
      System.out.printf("Document text length: %d%n", document.getText().length());
    }
  }
}

Node.js

For more information, see the Document AI Node.js API reference documentation.

To authenticate to Document AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'use strict';

const {DocumentProcessorServiceClient} = require('@google-cloud/documentai');
const {status} = require('@grpc/grpc-js');

const client = new DocumentProcessorServiceClient();

/**
 * Use the processDocument method
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id')
 * @param {string} locationId - The Google Cloud region where the service is located (for example, 'us-central1')
 * @param {string} processorId - The server-generated ID of the processor (for example, '1234567890abcdef'). Read from an existing processor.
 */
async function processDocument(projectId, locationId, processorId) {
  try {
    const name = `projects/${projectId}/locations/${locationId}/processors/${processorId}`;
    const rawDocument = {
      content: Buffer.from(
        '%PDF-1.3\n1 0 obj<</Pages 2 0 R>>endobj 2 0 obj<</Kids[3 0 R]/Count 1>>endobj 3 0 obj<</MediaBox[0 0 3 3]>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF'
      ),
      mimeType: 'application/pdf',
    };

    const request = {
      name,
      rawDocument,
    };

    const [response] = await client.processDocument(request);

    console.log('Document processed successfully.');
    if (response.document) {
      console.log(`Document text: ${response.document.text || ''}`);
      console.log(`Page count: ${response.document.pages ? response.document.pages.length : 0}`);
    }
  } catch (err) {
    if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument: ${err.message}`);
    } else if (err.code === status.NOT_FOUND) {
      console.error(`Resource not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code) {
      console.error(`API error (code ${err.code}): ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { processDocument };

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.