FileDummy Logo
FileDummy
Xử Lý & Chuyển Đổi Định Dạng

Trích Xuất Văn Bản Từ File PDF Bằng JavaScript & Node.js

Cách trích xuất text từ tệp PDF bằng thư viện pdf-parse trong Node.js và PDF.js trên trình duyệt. Tải file PDF mẫu để kiểm thử.

20 tháng 9, 202611 phút đọc1,420 lượt xem
nodejspdftext-extractionpdfjspdf-parse

Extracting structured text from PDFs is a core component of search indexing, invoice parsing, LLM retrieval-augmented generation (RAG), and data analysis. This guide shows how to extract raw text and layout data in JavaScript and Node.js.

Using pdf-parse in Node.js

pdf-parse is a lightweight Node.js library built on top of Mozilla's PDF.js:

Terminal
npm install pdf-parse
TypeScript
import fs from 'fs';
import pdf from 'pdf-parse';

export async function extractPdfText(filePath: string) {
  const dataBuffer = fs.readFileSync(filePath);

  const data = await pdf(dataBuffer);

  return {
    pageCount: data.numpages,
    text: data.text,
    info: data.info,
    metadata: data.metadata,
  };
}
Verified Test Asset.pdf

Download our structured 5MB PDF test file to test text extraction, page counts, and metadata inspection.

Tải File Mẫu 5MB PDF →

Extracting Text in the Browser with PDF.js

Mozilla's pdfjs-dist allows client-side parsing without server roundtrips:

TypeScript
import * as pdfjsLib from 'pdfjs-dist';

// Set worker source
pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

export async function extractTextInBrowser(file: File): Promise<string> {
  const arrayBuffer = await file.arrayBuffer();
  const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
  let fullText = '';

  for (let i = 1; i <= pdf.numPages; i++) {
    const page = await pdf.getPage(i);
    const content = await page.getTextContent();
    const pageText = content.items.map((item: any) => item.str).join(' ');
    fullText += `--- Page ${i} ---\n${pageText}\n\n`;
  }

  return fullText;
}

Handling Text Extraction Gotchas

  • Two-column layouts: Text extractors reading stream order may read across columns instead of down.
  • Font encoding: Non-standard embedded font encodings can output garbled Unicode characters without appropriate character map tables.
NDL

Nguyễn Đại Long

Tác Giả

Backend Lead • Chuyên gia Kiến trúc Hệ thống Phân tán & Lưu trữ Đám mây

Hơn 4 năm kinh nghiệm thiết kế các hệ thống xử lý tệp tải lên thông lượng lớn, tối ưu hóa cơ sở dữ liệu và hạ tầng phân tán Cloudflare R2 / AWS S3. Người sáng lập FileDummy và Mạng lưới Hệ sinh thái NDL.

Bài viết này có hữu ích không?

Bấm Thích để ủng hộ tác giả và giúp bài viết lan tỏa tới cộng đồng lập trình viên.

Thảo Luận Kỹ Thuật & Đóng Góp Ý Kiến (0)

Chia sẻ kết quả benchmark, phản hồi các trường hợp biên hoặc đặt câu hỏi chuyên môn.

0/3000

Chưa có bình luận nào. Hãy là lập trình viên đầu tiên bắt đầu cuộc thảo luận!

Câu Hỏi Thường Gặp (FAQ)

What is the difference between pdf-parse and pdfjs-dist?

pdf-parse is a lightweight wrapper returning all text as a single string. pdfjs-dist provides lower-level access to individual text items with their coordinates, enabling layout-aware extraction for columns and tables. Use pdf-parse for simple extraction, pdfjs-dist when you need positional data.

Why is extracted text garbled or in wrong order?

PDFs store text as glyphs at absolute positions with no inherent reading order. Correct extraction requires sorting by Y position (lines) then X position (left-to-right). For multi-column PDFs, cluster glyphs into columns first using pdfjs-dist's TextContent API.

How do I extract text from a scanned PDF?

Scanned PDFs contain images, not text, so OCR is required. Use Tesseract.js in Node.js: render each PDF page to canvas with pdfjs-dist, then pass the canvas image data to Tesseract.

Bài Viết Liên Quan