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

Tách & Ghép File PDF Trong Node.js Bằng Thư Viện pdf-lib (Thuần JS)

Thao tác ghép nhiều tài liệu PDF hoặc trích xuất từng trang riêng biệt bằng pdf-lib hoàn toàn trên bộ nhớ RAM. File mẫu 10MB có sẵn.

17 tháng 10, 202610 phút đọc1,420 lượt xem
nodejspdfpdf-libmerge-pdfsplit-pdf

Thao tác trang PDF — kết hợp nhiều báo cáo thành một tệp hoặc trích xuất các trang cụ thể — có thể được thực hiện hoàn toàn bằng JavaScript thuần túy mà không cần các phụ thuộc hệ thống bên ngoài như Poppler hay Ghostscript, nhờ thư viện pdf-lib.

Cài Đặt pdf-lib

Terminal
npm install pdf-lib
Thử Nghiệm Thực Tế.pdf

Tải file PDF mẫu 10MB nhiều trang để kiểm thử các hàm tách và ghép với pdf-lib.

Tải File Mẫu 10MB PDF →

Ghép Nhiều PDF

TypeScript
import { PDFDocument } from 'pdf-lib';
import fs from 'fs';

export async function mergePdfFiles(pdfBuffers: Buffer[]): Promise<Uint8Array> {
  const mergedPdf = await PDFDocument.create();

  for (const buffer of pdfBuffers) {
    const donorPdf = await PDFDocument.load(buffer);
    const copiedPages = await mergedPdf.copyPages(donorPdf, donorPdf.getPageIndices());

    copiedPages.forEach((page) => mergedPdf.addPage(page));
  }

  return await mergedPdf.save();
}

Tách PDF (Trích Xuất Phạm Vi Trang)

TypeScript
import { PDFDocument } from 'pdf-lib';

export async function extractPdfPages(
  sourceBuffer: Buffer,
  pageIndices: number[] // số trang theo chỉ mục 0
): Promise<Uint8Array> {
  const sourcePdf = await PDFDocument.load(sourceBuffer);
  const newPdf = await PDFDocument.create();

  const copiedPages = await newPdf.copyPages(sourcePdf, pageIndices);
  copiedPages.forEach((page) => newPdf.addPage(page));

  return await newPdf.save();
}

Mẹo Hiệu Năng Trong Bộ Nhớ

  • Giữ luồng byte trong bộ nhớ: Tránh ghi các tệp trung gian ra đĩa trong quá trình ghép nhiều bước.
  • Bảo toàn metadata: Sử dụng mergedPdf.setTitle('Báo Cáo Tổng Hợp') và mergedPdf.setAuthor('My App') để duy trì thuộc tính tài liệu gọn gàng.
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)

Does pdf-lib support password-protected PDFs?▾

pdf-lib can decrypt password-protected PDFs using the password option in PDFDocument.load(). The merged output is unencrypted by default. Re-encrypt with doc.encrypt() if required.

How do I merge large PDFs without running out of memory?▾

pdf-lib loads the entire PDF into memory. For very large PDFs (100MB+), use Ghostscript (gs -sDEVICE=pdfwrite -dBATCH -o merged.pdf input1.pdf input2.pdf) which processes pages in a streaming fashion.

Can I add page numbers when merging PDFs?▾

Yes. After copyPages(), use page.drawText() to add page numbers at any position. Embed a font first with doc.embedFont(). You can also add headers, watermarks, or bookmarks using the same drawing API.

Bài Viết Liên Quan