A utility for compressing and splitting PDF files using Ghostscript and PDF-Lib.
npm install pdf-compress-split-utilitysudo apt-get install ghostscript on Ubuntu).
sh
npm install pdf-compress-split-utility
`
Usage
$3
The compressPDF function compresses individual pages of a PDF to ensure they do not exceed the specified size limit.
`js
const { compressPDF } = require('pdf-compress-split-utility');
const path = require('path');
const inputPath = path.join(__dirname, 'path-to-your-pdf.pdf');
const KB = 1024;
(async () => {
try {
await compressPDF(inputPath, 900 * KB); // Compress pages to be under 900KB each
console.log('PDF pages compressed successfully');
} catch (err) {
console.error(err);
}
})();
`
$3
The splitPDF function splits a PDF file into smaller parts if the total file size exceeds the specified limit.
`js
const { splitPDF } = require('pdf-compress-split-utility');
const path = require('path');
const inputPath = path.join(__dirname, 'path-to-your-pdf.pdf');
const KB = 1024;
(async () => {
try {
await splitPDF(inputPath, 9 KB KB); // Split file to be under 9MB
console.log('PDF split successfully');
} catch (err) {
console.error(err);
}
})();
`
$3
You can combine both functions to first compress the pages and then split the PDF file if necessary.
`js
const { compressPDF, splitPDF } = require('pdf-compress-split-utility');
const path = require('path');
const inputPath = path.join(__dirname, 'path-to-your-pdf.pdf');
const KB = 1024;
(async () => {
try {
await compressPDF(inputPath, 900 * KB); // Compress pages to be under 900KB each
console.log('PDF pages compressed successfully');
await splitPDF(inputPath, 9 KB KB); // Split file to be under 9MB
console.log('PDF split successfully');
} catch (err) {
console.error(err);
}
})();
`
Notes
- Ensure Ghostscript is installed and accessible from your command line. Verify by running gs --version (Linux) or gswin64c --version / gswin32c --version (Windows).
- Adjust the paths and size limits (maxPageSize for compressPDF and maxFileSize for splitPDF`) as per your requirements.