| 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 |
| 76 | console.log('The document contains the following paragraphs:'); |
| 77 | const [page1] = document.pages; |
| 78 | const {paragraphs} = page1; |
| 79 | |
| 80 | for (const paragraph of paragraphs) { |
| 81 | const paragraphText = getText(paragraph.layout.textAnchor); |
| 82 | console.log(`Paragraph text:\n${paragraphText}`); |
| 83 | } |
| 84 | |
| 85 | // Form parsing provides additional output about |
| 86 | // form-formatted PDFs. You must create a form |
| 87 | // processor in the Cloud Console to see full field details. |
| 88 | console.log('\nThe following form key/value pairs were detected:'); |
| 89 | |
| 90 | const {formFields} = page1; |
| 91 | for (const field of formFields) { |