寻求LibreOffice命令行PDF压缩方案(替代GS解决并发问题)
LibreOffice Command Line for PDF Compression (Replacing GS)
Here's a direct command line equivalent to your Ghostscript script, optimized for screen-quality compression with better concurrency support:
libreoffice --headless --convert-to pdf:"writer_pdf_Export:CompressImages=true:ImageQuality=10:ReduceImageResolution=true:MaxImageResolution=72:UseLosslessCompression=false:PDFVersion=1.4" --outdir ./output_directory input.pdf
Parameter Breakdown (Matching Your GS Settings):
--headless: Runs LibreOffice without a GUI (critical for server/Node.js environments)pdf:"writer_pdf_Export:...: Specifies PDF export with custom filter settingsCompressImages=true: Enables image compressionImageQuality=10: Low-quality compression (0-100; lower = smaller file size)ReduceImageResolution=true: Downscales images to the specified DPIMaxImageResolution=72: Matches GS's/screenresolution (72 DPI)UseLosslessCompression=false: Uses lossy compression to minimize file sizePDFVersion=1.4: Aligns with GS's-dCompatibilityLevel=1.4
--outdir ./output_directory: Outputs the compressed PDF to the specified directory (prevents overwriting the input file)
Notes for Node.js Integration:
- Cross-OS Compatibility: On some systems (e.g., older Linux distros), replace
libreofficewithsoffice - Custom Output Filename: LibreOffice uses the input filename for the output. To rename it, add a file rename step after running the command (use Node's
fs.rename()orfs.promises.rename()for async operations) - Concurrency: Unlike GS, you can run multiple LibreOffice instances in parallel (each command spawns an independent process) without locking issues
- Complex PDFs: If the input PDF has heavy graphics or complex layouts, replace
writer_pdf_Exportwithdraw_pdf_Exportfor better formatting retention
Example Node.js Snippet (Async/Await):
const { exec } = require('child_process'); const util = require('util'); const fs = require('fs').promises; const execPromise = util.promisify(exec); async function compressPDF(inputPath, outputPath) { const tempDir = './temp_pdf_output'; await fs.mkdir(tempDir, { recursive: true }); // Execute LibreOffice compression command await execPromise(`libreoffice --headless --convert-to pdf:"writer_pdf_Export:CompressImages=true:ImageQuality=10:ReduceImageResolution=true:MaxImageResolution=72:UseLosslessCompression=false:PDFVersion=1.4" --outdir ${tempDir} ${inputPath}`); // Rename output to desired path const inputFilename = inputPath.split('/').pop(); const tempOutput = `${tempDir}/${inputFilename}`; await fs.rename(tempOutput, outputPath); // Clean up temporary directory await fs.rm(tempDir, { recursive: true }); } // Usage example compressPDF('./original.pdf', './compressed.pdf') .then(() => console.log('PDF compression completed')) .catch(err => console.error('Compression failed:', err));
内容的提问来源于stack exchange,提问作者SYED TOUSIF
相关产品推荐
相关产品推荐

