문서 처리(v1)

지정된 프로세서를 사용하여 PDF 문서를 동기식으로 처리합니다.

코드 샘플

Java

자세한 내용은 Document AI Java API 참고 문서를 참조하세요.

Document AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Document AI Node.js API 참고 문서를 참조하세요.

Document AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

'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 };

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저 참조하기