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ử.
Trích xuất văn bản có cấu trúc từ PDF là thành phần cốt lõi của lập chỉ mục tìm kiếm, phân tích hóa đơn, LLM retrieval-augmented generation (RAG) và phân tích dữ liệu. Hướng dẫn này trình bày cách trích xuất văn bản thô và dữ liệu bố cục trong JavaScript và Node.js.
Sử Dụng pdf-parse Trong Node.js
pdf-parse là thư viện Node.js nhẹ được xây dựng trên PDF.js của Mozilla:
npm install pdf-parse
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,
};
}
Tải file PDF test 5MB có cấu trúc để kiểm thử trích xuất văn bản, đếm trang và kiểm tra metadata.
Tải File Mẫu 5MB PDF →Trích Xuất Văn Bản Trên Trình Duyệt Với PDF.js
pdfjs-dist của Mozilla cho phép phân tích phía client mà không cần roundtrip đến máy chủ:
import * as pdfjsLib from 'pdfjs-dist';
// Thiết lập nguồn worker
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 += `--- Trang ${i} ---\n${pageText}\n\n`;
}
return fullText;
}
Xử Lý Các Vấn Đề Thường Gặp Khi Trích Xuất Văn Bản
- Bố cục hai cột: Các bộ trích xuất đọc theo thứ tự stream có thể đọc ngang qua các cột thay vì đọc xuống.
- Mã hóa font: Các bảng mã hóa font nhúng không chuẩn có thể xuất ra các ký tự Unicode bị lỗi mà không có bảng ánh xạ ký tự phù hợp.
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.
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.