pdf-parse

repository·main·Indexed 42 days ago

https://github.com/mehmet-kozan/pdf-parse

A pure TypeScript, cross-platform module and CLI for extracting text, images, and tabular data from PDFs. Version 3.0.0-beta.0 supports Node.js (v20, v22, v23, v24) and browser environments, including integration with React, Vue, and Angular. Features include PDF metadata extraction via getInfo, page rendering via getScreenshot, and a dedicated CLI for terminal-based extraction.

Tokens
17K
Snippets
71
Records
90
Agent score
52%

What's inside pdf-parse

  1. When to manually set the PDF worker

    main

    While pdf-parse handles worker configuration automatically in most environments, manual configuration via PDFParse.setWorker() is required in the following scenarios:

    Node.js/Backend:

    • Custom builds where the worker cannot be resolved automatically.
    • Monorepo/workspace setups (e.g., pnpm, yarn PnP) where node_modules layout is non-standard.
    • Electron/NW.js packaging with non-standard import paths.
    • Self-hosting worker files for offline or security requirements.

    Browser:

    • Using a custom build of pdf-parse.
    • Self-hosting worker files for security or offline requirements.
    • Using a different CDN provider.
  2. Migrate from v1 to v2/v3

    main

    In v1, pdf-parse was used as a function. In v2 and v3, you must instantiate the PDFParse class.

    v1 pattern (Legacy):

    const pdf = require('pdf-parse');
    pdf(buffer).then(result => console.log(result.text));

    v2/v3 pattern (Current):

    const { PDFParse } = require('pdf-parse');
    // or import { PDFParse } from 'pdf-parse';
    
    async function run() {
      const parser = new PDFParse({ url: 'https://example.com/file.pdf' });
      const result = await parser.getText();
      console.log(result.text);
    }
    run();
    const { PDFParse } = require('pdf-parse');
    
    async function run() {
    	const parser = new PDFparse({ url: 'https://bitcoin.org/bitcoin.pdf' });
    
    	const result = await parser.getText();
    	// or use getRaw() for v1 compatibility
    	console.log(result.text);
    }
    
    run();
  3. Install pdf-parse via npm, pnpm, yarn, or bun

    main

    To use pdf-parse in your project, install it using your preferred package manager:

    npm install pdf-parse
    # or
    pnpm add pdf-parse
    # or
    yarn add pdf-parse
    # or
    bun add pdf-parse
    npm install pdf-parse
  4. Configure the worker in Node.js (ES Modules)

    main

    For ES Modules in Node.js, you can configure the worker using import.meta.resolve (available in Node.js 20.6+) or via manual path resolution for older versions. The worker path must be converted to a file:// URL. Call PDFParse.setWorker(workerUrl) before initializing PDFParse.

    import { PDFParse } from 'pdf-parse';
    import { pathToFileURL } from 'url';
    import { fileURLToPath } from 'url';
    import { dirname, resolve } from 'path';
    
    // Option 1: Using import.meta.resolve (Node.js 20.6+)
    const workerUrl = pathToFileURL(
        fileURLToPath(await import.meta.resolve('pdfjs-dist/legacy/build/pdf.worker.mjs'))
    ).href;
    
    // Option 2: Manual path resolution (compatible with older Node.js versions)
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    const workerPath = resolve(__dirname, 'node_modules/pdfjs-dist/legacy/build/pdf.worker.mjs');
    const workerUrl = pathToFileURL(workerPath).href;
    
    // Set worker before creating PDFParse instances
    PDFParse.setWorker(workerUrl);
    
    // Now you can use PDFParse
  5. Install the pdf-parse CLI globally

    main

    For command-line usage, install the package globally. You can use npm install -g to install, npm update -g to update, and npm uninstall -g to remove it. Use pdf-parse -h to view the help menu.

    # installation
    npm install -g pdf-parse
    
    # updating
    npm update -g pdf-parse
    
    # uninstallation
    npm uninstall -g pdf-parse
    
    # help
    pdf-parse -h
  6. Optimize processing for large PDF files

    main

    For PDF files larger than 5MB, use the --large flag to enable performance optimizations. This flag enables:

    • Disabling auto-fetching of additional pages
    • Chunk-based loading instead of streaming
    • Optimized range request chunk size
    pdf-parse text https://example.com/large-document.pdf --large --pages 1-10
  7. Generate test, coverage, and benchmark reports locally

    main

    You can generate project reports (test results, code coverage, and benchmarks) locally using the provided npm scripts. These reports are stored in the reports/ directory.

    To build the reports, run:

    npm run report:build

    To generate the reports directly, run:

    npm run report
  8. Fix 'Cannot find module' in Serverless or Edge environments

    main

    When deploying to Next.js (Vercel), Edge Functions, AWS Lambda, Netlify, or Cloudflare Workers, you may encounter module resolution errors.

    General Fix

    Import the worker module before importing pdf-parse:

    // ESM
    import 'pdf-parse/worker';
    import {PDFParse} from 'pdf-parse';
    
    // CJS
    require ('pdf-parse/worker');
    const {PDFParse} = require('pdf-parse');

    Next.js / Vercel Specific Configuration

    To ensure Next.js includes the necessary modules for serverless execution, add pdf-parse and @napi-rs/canvas to serverExternalPackages in your next.config.ts:

    import type { NextConfig } from "next";
    
    const nextConfig: NextConfig = {
      serverExternalPackages: ["pdf-parse", "@napi-rs/canvas"],
    };
    
    export default nextConfig;
    import type { NextConfig } from "next";
    
    const nextConfig: NextConfig = {
      serverExternalPackages: ["pdf-parse", "@napi-rs/canvas"],
    };
    
    export default nextConfig;