convert docx file to pdf file
npm install docx2pdf-converterbash
npm i docx2pdf-converter
`
Usage
$3
This line of code converts a single DOCX file into a PDF file:
`javascript
const topdf = require('docx2pdf-converter');
const inputPath = './report.docx';
topdf.convert(inputPath, 'output.pdf');
`
$3
This code converts all DOCX files within a directory to PDFs and saves them to another directory:
`javascript
const fs = require('fs');
const path = require('path');
const { convert, resolvePaths } = require('docx2pdf-converter');
function convertDirectory(inputDir, outputDir) {
const files = fs.readdirSync(inputDir);
files.forEach((file) => {
if (file.endsWith('.docx')) {
const inputPath = path.join(inputDir, file);
const { output } = resolvePaths(inputPath, outputDir);
convert(inputPath, output);
console.log(Converted: ${file});
}
});
}
/*
Assume both directories (input and output) are in the same folder.
If not, you can provide absolute paths to the folders.
*/
const inputDirectory = './inputdir';
const outputDirectory = './outputdir';
convertDirectory(inputDirectory, outputDirectory);
`
$3
The extractImages function allows you to extract all images from a DOCX file and save them to a specified directory:
`javascript
const { extractImages } = require('docx2pdf-converter');
const inputPath = './report.docx'; // Path to your DOCX file
const outputDir = './extracted-images'; // Directory where images will be saved
extractImages(inputPath, outputDir);
`
This will extract any images embedded in the DOCX file and save them in the extracted-images directory.
API
$3
Description: Converts a DOCX file to PDF.
Parameters:
- inputPath (string): Path to the input DOCX file.
- outputPath (string): Path to the output PDF file.
- keepActive (boolean, optional): Flag to keep the application active (platform-dependent).
Returns: Nothing. It performs the conversion.
$3
Description: Extracts images from a DOCX file and saves them to the specified directory.
Parameters:
- inputPath (string): Path to the input DOCX file.
- outputDir (string): Directory where the extracted images will be saved.
Returns: Nothing. It extracts the images and logs the status.
$3
Description: Resolves and validates input and output paths, ensuring they are correct and handle both single files and directories.
Parameters:
- inputPath (string): Path to the input DOCX file or directory.
- outputPath (string, optional): Path to the output directory or file.
Returns: An object containing resolved input and output paths, and a batch flag indicating whether it's batch processing.
Platform-Specific Support
- Windows: Uses PowerShell scripts (convert.ps1 and convertTodocx.ps1) for converting DOCX to PDF and vice versa.
- macOS: Uses a shell script (convert.sh) for converting DOCX to PDF.
- Linux: Uses unoconv to convert DOCX to PDF.
The convert` function automatically detects the platform and uses the appropriate method for conversion.