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

Chuyển Đổi PDF Sang Word DOCX Bằng Node.js

Hướng dẫn chuyển đổi tài liệu PDF thành file Word DOCX có thể chỉnh sửa bằng Node.js và LibreOffice headless. Code mẫu hoàn chỉnh và file test.

14 tháng 9, 202610 phút đọc1,420 lượt xem
nodejspdfdocxconversionlibreoffice

Converting PDF documents into editable Microsoft Word (.docx) files is a common requirement for legal portals, contract review platforms, and document management systems. Because PDF is primarily a display format (specifying absolute glyph coordinates) rather than a semantic structure, conversion requires structural reconstruction.

Conversion Approaches in Node.js

  1. LibreOffice Headless (Self-Hosted): High fidelity, converts complex tables and layouts via command line.
  2. Cloud Converter APIs (ConvertAPI, CloudConvert): Zero maintenance, handles OCR and rasterized text.
  3. pdf2docx (Python bridge via Node child_process): High quality for vector documents and tables.
Verified Test Asset.pdf

Download our 10MB PDF sample file to test your PDF-to-DOCX conversion pipeline.

Tải File Mẫu 10MB PDF →

Using Headless LibreOffice with Node.js

Running LibreOffice in headless mode inside a Docker container provides free, reliable document conversion:

TypeScript
import { exec } from 'child_process';
import util from 'util';
import path from 'path';
import fs from 'fs';

const execPromise = util.promisify(exec);

export async function convertPdfToDocx(inputPdfPath: string, outputDir: string): Promise<string> {
  if (!fs.existsSync(inputPdfPath)) {
    throw new Error('Input PDF does not exist.');
  }

  // soffice is the executable name for LibreOffice
  const cmd = `soffice --headless --convert-to docx "${inputPdfPath}" --outdir "${outputDir}"`;

  console.log('Executing conversion:', cmd);
  const { stdout, stderr } = await execPromise(cmd);

  if (stderr && !stderr.includes('Warning')) {
    console.warn('LibreOffice warnings:', stderr);
  }

  const baseName = path.basename(inputPdfPath, path.extname(inputPdfPath));
  const expectedOutputPath = path.join(outputDir, `${baseName}.docx`);

  if (!fs.existsSync(expectedOutputPath)) {
    throw new Error('Conversion completed but output DOCX file was not generated.');
  }

  return expectedOutputPath;
}

Key Conversion Challenges

  • Embedded fonts: Missing system fonts can cause text overlapping and reflow issues. Install standard Microsoft Core Fonts (msttcorefonts) in your Linux/Docker host.
  • Scanned pages: PDFs containing only raster images require an Optical Character Recognition (OCR) step using Tesseract before conversion.
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)

Why is PDF to DOCX conversion difficult?

PDF is a fixed-layout format storing glyphs at absolute coordinates with no concept of paragraphs or flowing text. Converting to DOCX requires reconstructing document structure from raw coordinates, which is inherently imperfect for complex layouts.

What is the best free tool for PDF to DOCX in Node.js?

LibreOffice in headless mode (libreoffice --headless --convert-to docx) is the most reliable free option. Call it from Node.js using child_process.exec(). For better accuracy, Adobe PDF Services and Aspose.Words offer commercial Node.js SDKs.

Can I convert a scanned PDF to DOCX in Node.js?

Scanned PDFs need OCR first. Use Tesseract.js (open source) or Google Cloud Vision / AWS Textract. After OCR, reconstruct the text as DOCX using the docx library.

Bài Viết Liên Quan