Batch annotate files (v1p4beta1)

Synchronously detect document text in a PDF file stored in Cloud Storage using batch file annotation.

Code sample

Java

Before trying this sample, follow the Java setup instructions in the Vision quickstart using client libraries. For more information, see the Vision Java API reference documentation.

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

import com.google.cloud.vision.v1p4beta1.AnnotateFileRequest;
import com.google.cloud.vision.v1p4beta1.AnnotateFileResponse;
import com.google.cloud.vision.v1p4beta1.AnnotateImageResponse;
import com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse;
import com.google.cloud.vision.v1p4beta1.Feature;
import com.google.cloud.vision.v1p4beta1.GcsSource;
import com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient;
import com.google.cloud.vision.v1p4beta1.InputConfig;
import java.util.Collections;
import java.util.List;

public class BatchAnnotateFiles {

  public static void main(String[] args) throws Exception {
    batchAnnotateFiles();
  }

  public static void batchAnnotateFiles() throws Exception {
    // Initialize the client with Application Default Credentials
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
      GcsSource gcsSource =
          GcsSource.newBuilder()
              .setUri("gs://cloud-samples-data/vision/document_understanding/kafka.pdf")
              .build();

      InputConfig inputConfig =
          InputConfig.newBuilder()
              .setMimeType("application/pdf")
              .setGcsSource(gcsSource)
              .build();

      Feature feature =
          Feature.newBuilder()
              .setType(Feature.Type.DOCUMENT_TEXT_DETECTION)
              .build();

      AnnotateFileRequest fileRequest =
          AnnotateFileRequest.newBuilder()
              .setInputConfig(inputConfig)
              .addFeatures(feature)
              .addPages(1)
              .build();

      // The API accepts a single AnnotateFileRequest in the batch
      List<AnnotateFileRequest> requests = Collections.singletonList(fileRequest);

      BatchAnnotateFilesResponse response = client.batchAnnotateFiles(requests);
      for (AnnotateFileResponse fileResponse : response.getResponsesList()) {
        System.out.printf("Total pages: %d%n", fileResponse.getTotalPages());
        for (AnnotateImageResponse pageResponse : fileResponse.getResponsesList()) {
          System.out.printf("Page full text: %s%n", pageResponse.getFullTextAnnotation().getText());
        }
      }
    }
  }
}

What's next

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