Okay, this is a challenging request because DOCX and PDF are complex binary formats, and rendering DOCX accurately into PDF usually requires a sophisticated layout engine (like those found in word processors or dedicated libraries often written in C/C++). Pure JavaScript solutions that handle this perfectly without relying on external binaries (like LibreOffice or a headless browser engine) are rare.
However, there's a promising approach using WebAssembly (WASM) which packages the necessary logic within the npm module itself, effectively meeting your criteria.
Recommended Solution: @nativedocuments/docx-wasm
This package aims to provide DOCX manipulation and conversion capabilities using WASM, bundling the necessary logic so you don't need separate system installations like LibreOffice or Pandoc.
Steps:
-
Install the package:
npm install @nativedocuments/docx-wasm
# or
yarn add @nativedocuments/docx-wasm
-
Create a Node.js script (e.g., convert.js):
const fs = require('fs').promises; // Use promises for async operations
const path = require('path');
const { Document } = require('@nativedocuments/docx-wasm');
async function convertDocxToPdf(docxPath, pdfPath) {
try {
console.log(`Reading DOCX file: ${docxPath}`);
const docxBuffer = await fs.readFile(docxPath);
console.log('Initializing Document processor...');
// Initialize the WASM module (this might take a moment the first time)
// await Document.init(); // Often initialization is handled implicitly on first use or via specific API calls if needed. Check package docs if direct init is required.
console.log('Loading DOCX data...');
const doc = await Document.load(docxBuffer, { ignore_images: false }); // Load the document buffer
console.log('Saving as PDF...');
const pdfBuffer = await doc.save_pdf(); // Perform the conversion to PDF buffer
console.log(`Writing PDF file: ${pdfPath}`);
await fs.writeFile(pdfPath, pdfBuffer);
console.log('Conversion successful!');
// Optional: Release resources if the library requires it (check docs)
// await doc.close();
} catch (error) {
console.error('Error during conversion:', error);
}
}
// --- Usage Example ---
const inputFile = path.join(__dirname, 'input.docx'); // Place your input.docx in the same directory
const outputFile = path.join(__dirname, 'output.pdf');
// Make sure an input.docx file exists before running!
fs.access(inputFile)
.then(() => convertDocxToPdf(inputFile, outputFile))
.catch(() => console.error(`Error: Input file not found at ${inputFile}`));
-
Place your DOCX file: Put your document named input.docx in the same directory as your convert.js script.
-
Run the script:
node convert.js
Important Considerations:
- Formatting Fidelity: While WASM solutions aim for high fidelity, converting complex DOCX layouts (like intricate tables, headers/footers, specific fonts, tracked changes, complex styling) to PDF perfectly is very hard. Expect potential differences compared to Microsoft Word or LibreOffice rendering. Test thoroughly with your specific documents.
- Performance: WASM initialization and processing can take time, especially for large or complex documents.
- Package Maintenance: Ensure the package is actively maintained and suits your needs.
- Error Handling: The example includes basic error handling, but you might need more robust error checking for production use.
- License: Check the license of the
@nativedocuments/docx-wasm package to ensure it's compatible with your project. (It appears to be Apache 2.0, which is generally permissive).
Alternative (If the above has limitations): mammoth + puppeteer
This is a two-step approach but still only relies on npm packages.
- Convert DOCX to HTML: Use
mammoth (pure JS) to convert DOCX to simple HTML.
- Convert HTML to PDF: Use
puppeteer (which bundles a Chromium browser) to render the HTML and print it to PDF.
This technically introduces a browser engine, but it's managed entirely by the puppeteer npm package, so you don't install Chrome/Chromium separately on the system.
npm install mammoth puppeteer
const fs = require('fs').promises;
const path = require('path');
const mammoth = require("mammoth");
const puppeteer = require('puppeteer');
async function convertDocxToPdfViaHtml(docxPath, pdfPath) {
let browser = null; // Define browser outside try block for finally
try {
console.log(`Reading DOCX file: ${docxPath}`);
const docxBuffer = await fs.readFile(docxPath);
console.log('Converting DOCX to HTML using Mammoth...');
const { value: html } = await mammoth.convertToHtml({ buffer: docxBuffer });
// Mammoth often generates basic HTML. You might need CSS for better styling.
// You could inject CSS here: const fullHtml = `<html><head><style>...</style></head><body>${html}</body></html>`;
const fullHtml = `<html><body>${html}</body></html>`; // Basic example
console.log('Launching Puppeteer (headless browser)...');
browser = await puppeteer.launch({ headless: true }); // Or 'new' for newer versions
const page = await browser.newPage();
console.log('Loading HTML into browser page...');
// Use setContent with waitUntil: 'networkidle0' to ensure images/resources load if HTML references external ones (less common with Mammoth output)
await page.setContent(fullHtml, { waitUntil: 'domcontentloaded' });
console.log('Generating PDF from page content...');
await page.pdf({
path: pdfPath,
format: 'A4', // Or 'Letter', etc.
printBackground: true // Include background colors/images
});
console.log(`PDF successfully written to ${pdfPath}`);
} catch (error) {
console.error('Error during conversion:', error);
} finally {
if (browser) {
console.log('Closing browser...');
await browser.close();
}
}
}
// --- Usage Example ---
const inputFile = path.join(__dirname, 'input.docx');
const outputFile = path.join(__dirname, 'output_via_html.pdf');
fs.access(inputFile)
.then(() => convertDocxToPdfViaHtml(inputFile, outputFile))
.catch(() => console.error(`Error: Input file not found at ${inputFile}`));
Pros/Cons of mammoth + puppeteer:
- Pros: High-fidelity HTML-to-PDF rendering via Chromium. Relatively common approach.
- Cons: Two-step process. Formatting loss during DOCX -> HTML conversion by Mammoth is possible (Mammoth focuses on semantic content, less on exact layout).
puppeteer downloads a large browser binary (~100-300MB) during npm install, which might be undesirable.
Choose the @nativedocuments/docx-wasm approach first, as it directly targets your requirement. If its formatting fidelity isn't sufficient for your specific DOCX files, the mammoth + puppeteer route is a viable fallback, although it involves an intermediate HTML step and a larger dependency footprint due to the bundled browser.