MCPcopy Create free account
hub / github.com/GoogleCloudPlatform/nodejs-docs-samples / main

Function main

document-ai/process-document.js:18–101  ·  view source on GitHub ↗
(projectId, location, processorId, filePath)

Source from the content-addressed store, hash-verified

16'use strict';
17
18async function main(projectId, location, processorId, filePath) {
19 // [START documentai_process_document]
20 /**
21 * TODO(developer): Uncomment these variables before running the sample.
22 */
23 // const projectId = 'YOUR_PROJECT_ID';
24 // const location = 'YOUR_PROJECT_LOCATION'; // Format is 'us' or 'eu'
25 // const processorId = 'YOUR_PROCESSOR_ID'; // Create processor in Cloud Console
26 // const filePath = '/path/to/local/pdf';
27
28 const {DocumentProcessorServiceClient} =
29 require('@google-cloud/documentai').v1;
30
31 // Instantiates a client
32 const client = new DocumentProcessorServiceClient();
33
34 async function processDocument() {
35 // The full resource name of the processor, e.g.:
36 // projects/project-id/locations/location/processor/processor-id
37 // You must create new processors in the Cloud Console first
38 const name = `projects/${projectId}/locations/${location}/processors/${processorId}`;
39
40 // Read the file into memory.
41 const fs = require('fs').promises;
42 const imageFile = await fs.readFile(filePath);
43
44 // Convert the image data to a Buffer and base64 encode it.
45 const encodedImage = Buffer.from(imageFile).toString('base64');
46
47 const request = {
48 name,
49 rawDocument: {
50 content: encodedImage,
51 mimeType: 'application/pdf',
52 },
53 };
54
55 // Recognizes text entities in the PDF document
56 const [result] = await client.processDocument(request);
57 const {document} = result;
58
59 // Get all of the document text as one big string
60 const {text} = document;
61
62 // Extract shards from the text field
63 const getText = textAnchor => {
64 if (!textAnchor.textSegments || textAnchor.textSegments.length === 0) {
65 return '';
66 }
67
68 // First shard in document doesn't have startIndex property
69 const startIndex = textAnchor.textSegments[0].startIndex || 0;
70 const endIndex = textAnchor.textSegments[0].endIndex;
71
72 return text.substring(startIndex, endIndex);
73 };
74
75 // Read the text recognition output from the processor

Callers 1

Calls 1

processDocumentFunction · 0.70

Tested by

no test coverage detected