To convert a DOCX document to PDF in a Node.js environment without relying on external dependencies beyond an npm package, you can use the @pspdfkit/nodejs library. This package provides a straightforward API for document conversion and operates independently of third-party tools like LibreOffice or Microsoft Office.
Installation:
Begin by installing the @pspdfkit/nodejs package:
npm install @pspdfkit/nodejs
Usage:
Here's how you can convert a DOCX file to PDF using this library:
const fs = require('fs');
const { load } = require('@pspdfkit/nodejs');
async function convertDocxToPdf(inputPath, outputPath) {
try {
// Read the DOCX file
const docxFile = fs.readFileSync(inputPath);
// Load the document
const instance = await load({ document: docxFile });
// Export to PDF
const pdfBuffer = await instance.exportPDF();
// Write the PDF to the output path
fs.writeFileSync(outputPath, Buffer.from(pdfBuffer));
// Close the instance
await instance.close();
console.log(`Conversion successful: ${outputPath}`);
} catch (error) {
console.error('Error during conversion:', error);
}
}
// Example usage
convertDocxToPdf('input.docx', 'output.pdf');
Notes:
-
By default, the resulting PDF will include a PSPDFKit watermark. To remove this watermark, you'll need to specify the license property with a key and appName when calling the load() function. For details on obtaining a trial license key, please refer to the PSPDFKit documentation.
-
Ensure that your Node.js environment is compatible with the @pspdfkit/nodejs package requirements.
This approach allows you to perform DOCX to PDF conversions solely through an npm package, without additional external dependencies.