### Configuring pdf-parse with Options Source: https://context7.com/albertcui/pdf-parse/llms.txt This example shows how to use options with the pdf-parse module to control the parsing process. It demonstrates limiting the number of pages to parse and specifying a particular PDF.js version for rendering. ```javascript const fs = require('fs'); const pdf = require('pdf-parse'); let dataBuffer = fs.readFileSync('./large-document.pdf'); // Parse only first 5 pages using specific PDF.js version let options = { max: 5, // Parse only first 5 pages (0 = all pages) version: 'v2.0.550' // PDF.js version to use }; pdf(dataBuffer, options).then(function(data) { console.log(`Total pages: ${data.numpages}`); // e.g., 100 console.log(`Rendered pages: ${data.numrender}`); // 5 console.log(`Text length: ${data.text.length}`); // Access individual page data data.pageData.forEach((pageText, index) => { console.log(`Page ${index + 1}: ${pageText.substring(0, 50)}...`); }); }); ``` -------------------------------- ### Custom PDF Page Rendering Callback (JavaScript) Source: https://github.com/albertcui/pdf-parse/blob/master/README.md Illustrates how to define a custom function to control the page rendering process for PDF text extraction. This allows for customized output formats beyond plain text. The example shows how to process text content and manage whitespace. It requires the pdf-parse module and Node.js. ```javascript // default render callback function render_page(pageData) { //check documents https://mozilla.github.io/pdf.js/ let render_options = { //replaces all occurrences of whitespace with standard spaces (0x20). The default value is `false`. normalizeWhitespace: false, //do not attempt to combine same line TextItem's. The default value is `false`. disableCombineTextItems: false } return pageData.getTextContent(render_options) .then(function(textContent) { let lastY, text = ''; for (let item of textContent.items) { if (lastY == item.transform[5] || !lastY){ text += item.str; } else{ text += '\n' + item.str; } lastY = item.transform[5]; } return text; }); } let options = { pagerender: render_page } let dataBuffer = fs.readFileSync('path to PDF file...'); pdf(dataBuffer,options).then(function(data) { //use new format }); ``` -------------------------------- ### Select PDF.js Version for Parsing Source: https://context7.com/albertcui/pdf-parse/llms.txt This example demonstrates how to specify a particular PDF.js version for parsing PDF files. This is useful for ensuring compatibility with different PDF formats or features. It includes a fallback mechanism to the default version if the specified version fails. ```javascript const fs = require('fs'); const pdf = require('pdf-parse'); let dataBuffer = fs.readFileSync('./document.pdf'); // Available versions: 'default', 'v1.9.426', 'v1.10.88', 'v1.10.100', 'v2.0.550' let options = { version: 'v2.0.550' // Use latest version for newer PDF features }; pdf(dataBuffer, options) .then(function(data) { console.log(`Parsed using PDF.js version: ${data.version}`); console.log(`Pages: ${data.numpages}`); console.log(`Document title: ${data.info.Title}`); console.log(`Content preview: ${data.text.substring(0, 200)}...`); }) .catch(function(error) { console.error('Failed with version v2.0.550, trying default...'); // Fallback to default version return pdf(dataBuffer, { version: 'default' }); }) .then(function(data) { if (data) { console.log(`Successfully parsed with default version`); } }); ``` -------------------------------- ### Parse Local PDF File (JavaScript) Source: https://github.com/albertcui/pdf-parse/blob/master/README.md Demonstrates how to read a PDF file from the local filesystem and extract its text content using the pdf-parse module. It logs the number of pages, rendered pages, PDF information, metadata, pdf.js version, and the extracted text. Requires Node.js and the 'fs' module. ```javascript const fs = require('fs'); const pdf = require('pdf-parse'); let dataBuffer = fs.readFileSync('path to PDF file...'); pdf(dataBuffer).then(function(data) { // number of pages console.log(data.numpages); // number of rendered pages console.log(data.numrender); // PDF info console.log(data.info); // PDF metadata console.log(data.metadata); // PDF.js version // check https://mozilla.github.io/pdf.js/getting_started/ console.log(data.version); // PDF text console.log(data.text); }); ``` -------------------------------- ### PDF Parsing Options (JavaScript) Source: https://github.com/albertcui/pdf-parse/blob/master/README.md Defines the default options available for the pdf-parse module. These include `pagerender` for custom output formats, `max` to limit the number of pages parsed, and `version` to specify the pdf.js library version to use. This allows fine-tuning the parsing behavior. ```javascript const DEFAULT_OPTIONS = { // internal page parser callback // you can set this option, if you need another format except raw text pagerender: render_page, // max page number to parse max: 0, //check https://mozilla.github.io/pdf.js/getting_started/ version: 'v1.10.100' } ``` -------------------------------- ### Handle Exceptions when Parsing PDF (JavaScript) Source: https://github.com/albertcui/pdf-parse/blob/master/README.md Shows how to implement error handling when parsing a PDF file using the pdf-parse module. It wraps the parsing logic in a .then() block and provides a .catch() block to log any errors that occur during the process. This ensures robustness when dealing with potentially invalid or corrupted PDF files. ```javascript const fs = require('fs'); const pdf = require('pdf-parse'); let dataBuffer = fs.readFileSync('path to PDF file...'); pdf(dataBuffer).then(function(data) { // use data }) .catch(function(error){ // handle exceptions }) ``` -------------------------------- ### Basic PDF Text Extraction with pdf-parse Source: https://context7.com/albertcui/pdf-parse/llms.txt This snippet demonstrates the basic usage of the pdf-parse module to extract text content, metadata, and page information from a PDF file. It reads a PDF file into a buffer and then uses the pdf-parse function to process it. ```javascript const fs = require('fs'); const pdf = require('pdf-parse'); // Read PDF file as buffer let dataBuffer = fs.readFileSync('./document.pdf'); // Parse PDF and extract text pdf(dataBuffer).then(function(data) { // Total number of pages in PDF console.log(data.numpages); // e.g., 14 // Number of pages actually rendered console.log(data.numrender); // e.g., 14 // PDF document metadata console.log(data.info); // { Title: 'My Document', Author: 'John Doe', ... } // PDF metadata object console.log(data.metadata); // PDF.js version used for parsing console.log(data.version); // e.g., '1.10.100' // Extracted text content from all pages console.log(data.text); // 'Full text content from PDF...' // Array of text content per page console.log(data.pageData); // ['Page 1 text...', 'Page 2 text...', ...] }); ``` -------------------------------- ### Error Handling for PDF Parsing with pdf-parse Source: https://context7.com/albertcui/pdf-parse/llms.txt This code demonstrates how to handle potential errors during PDF parsing using the pdf-parse module. It includes a .catch block to manage exceptions and provides specific error messages for common issues like invalid or password-protected PDFs. ```javascript const fs = require('fs'); const pdf = require('pdf-parse'); let dataBuffer = fs.readFileSync('./corrupted-document.pdf'); pdf(dataBuffer) .then(function(data) { console.log(`Successfully parsed ${data.numpages} pages`); console.log(`Extracted ${data.text.length} characters`); // Write extracted text to file fs.writeFileSync('./output.txt', data.text, 'utf8'); }) .catch(function(error) { console.error('PDF parsing failed:', error.message); // Handle specific error scenarios if (error.message.includes('Invalid PDF')) { console.error('File is not a valid PDF document'); } else if (error.message.includes('password')) { console.error('PDF is password protected'); } else { console.error('Unknown error occurred during parsing'); } }); ``` -------------------------------- ### Custom Page Rendering Logic with pdf-parse Source: https://context7.com/albertcui/pdf-parse/llms.txt This snippet illustrates how to implement custom page rendering logic with pdf-parse to control the format of extracted text. It defines a `customRenderPage` function that processes text content with specific rendering options. ```javascript const fs = require('fs'); const pdf = require('pdf-parse'); // Custom render function to format page content function customRenderPage(pageData) { let render_options = { normalizeWhitespace: true, // Normalize whitespace to standard spaces disableCombineTextItems: false // Combine text items on same line }; return pageData.getTextContent(render_options) .then(function(textContent) { let lastY, text = ''; // Process each text item for (let item of textContent.items) { // Check if item is on same line as previous item if (lastY == item.transform[5] || !lastY) { text += item.str; } else { text += '\n' + item.str; } lastY = item.transform[5]; } return text; }); } let dataBuffer = fs.readFileSync('./document.pdf'); let options = { pagerender: customRenderPage }; pdf(dataBuffer, options).then(function(data) { console.log('Custom formatted text:', data.text); }); ``` -------------------------------- ### Batch Process Multiple PDFs Source: https://context7.com/albertcui/pdf-parse/llms.txt This asynchronous function processes a list of PDF files sequentially. For each file, it reads the buffer, parses the PDF, saves the extracted text to a corresponding .txt file, and collects results including success status, page count, and text length. Error handling is included for individual file processing. ```javascript const fs = require('fs'); const pdf = require('pdf-parse'); const path = require('path'); async function processPDFBatch(fileList) { let results = []; for (let filePath of fileList) { try { console.log(`Processing: ${filePath}`); let dataBuffer = fs.readFileSync(filePath); let data = await pdf(dataBuffer, { max: 0 }); results.push({ file: path.basename(filePath), success: true, pages: data.numpages, textLength: data.text.length, title: data.info?.Title || 'Untitled', author: data.info?.Author || 'Unknown' }); // Save extracted text let outputPath = filePath.replace('.pdf', '.txt'); fs.writeFileSync(outputPath, data.text, 'utf8'); } catch (error) { results.push({ file: path.basename(filePath), success: false, error: error.message }); } } return results; } // Process multiple PDFs let pdfFiles = [ './documents/report1.pdf', './documents/report2.pdf', './documents/report3.pdf' ]; processPDFBatch(pdfFiles).then(results => { console.log(' Processing Summary:'); results.forEach(result => { if (result.success) { console.log(`✓ ${result.file}: ${result.pages} pages, ${result.textLength} chars`); } else { console.log(`✗ ${result.file}: ${result.error}`); } }); }); ``` -------------------------------- ### Extract PDF Content as JSON Source: https://context7.com/albertcui/pdf-parse/llms.txt This snippet shows how to render PDF page content as a structured JSON object. It utilizes the `pagerender` option to customize the output, extracting text items with their positional and dimensional properties. The result is a JSON string containing an array of text items and their count. ```javascript const fs = require('fs'); const pdf = require('pdf-parse'); // Render page as structured JSON object function renderPageAsJSON(pageData) { let render_options = { normalizeWhitespace: false, disableCombineTextItems: false }; return pageData.getTextContent(render_options) .then(function(textContent) { // Extract structured data let items = textContent.items.map(item => ({ text: item.str, x: item.transform[4], y: item.transform[5], width: item.width, height: item.height })); return JSON.stringify({ items: items, itemCount: items.length }); }); } let dataBuffer = fs.readFileSync('./invoice.pdf'); let options = { pagerender: renderPageAsJSON, max: 1 // Process only first page }; pdf(dataBuffer, options).then(function(data) { console.log('Metadata:', data.info); // Parse JSON from each page data.pageData.forEach((jsonString, index) => { let pageData = JSON.parse(jsonString); console.log(`Page ${index + 1} has ${pageData.itemCount} text items`); }); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.