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

Function main

document-ai/process-document-ocr.js:18–161  ·  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_ocr_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').v1beta3;
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
58 console.log('Document processing complete.');
59
60 // Read the text recognition output from the processor
61 // For a full list of Document object attributes,
62 // please reference this page: https://googleapis.dev/nodejs/documentai/latest/index.html
63 const {document} = result;
64 const {text} = document;
65
66 // Read the text recognition output from the processor
67 console.log(`Full document text: ${JSON.stringify(text)}`);
68 console.log(`There are ${document.pages.length} page(s) in this document.`);
69 for (const page of document.pages) {
70 console.log(`Page ${page.pageNumber}`);
71 printPageDimensions(page.dimension);
72 printDetectedLanguages(page.detectedLanguages);
73 printParagraphs(page.paragraphs, text);
74 printBlocks(page.blocks, text);
75 printLines(page.lines, text);

Callers 1

Calls 1

processDocumentFunction · 0.70

Tested by

no test coverage detected