如何在Node.js中通过ghostscript4js获取PDF文档页数
问题解决:Node.js中使用ghostscript4js获取PDF页数失败
问题分析
你在命令行中能正常通过Ghostscript命令获取PDF页数,但在Node.js的Pagecount函数中无法正确返回数值,核心原因是命令参数的拆分格式错误——ghostscript4js的execute方法对参数数组的要求和命令行直接执行不同,不能将-c后的脚本内容作为带引号的单个元素传递。
解决方案
修改Pagecount函数中的命令参数数组,调整参数拆分方式,并优化脚本写法:
修改后的完整代码
const omnis_calls = require('omnis_calls'); const gs = require('ghostscript4js'); // 补全缺失的模块引入 let autoSendResponse = true; 'use strict' const methodMap = { Pagecount: async function(param, response) { autoSendResponse = false; const pdfPath = param.C1; // 按Ghostscript参数规则拆分每个元素,-c与脚本内容分离 const cmd = [ '-q', '-dNODISPLAY', '-dNOSAFER', `--permit-file-read=${pdfPath}`, '-c', `("${pdfPath}") (r) file runpdfbegin pdfpagecount = quit` ]; gs.execute(cmd) .then(function (value) { // 清理输出中的空白字符,提取纯净页数数值 const pageCount = value.trim(); const obj = { err: 0, message: pageCount }; omnis_calls.sendResponse(obj, response); }) .catch((err) => { const obj = { err: 1, message: err.toString() }; omnis_calls.sendResponse(obj, response); }); }, GSVersion: function (param, response) { autoSendResponse = false; let version = gs.version(); const obj = { err: 0, message: version }; omnis_calls.sendResponse(obj, response); } }; module.exports = { call: function (method, param, response) { autoSendResponse = true; if (methodMap[method]) { const result = methodMap[method](param, response); if (autoSendResponse) omnis_calls.sendResponse(result, response); return true; } else { throw Error(`Method '${method}' does not exist`); } } };
关键修改说明
- 补全模块引入:原代码缺少
ghostscript4js的引入语句,这是执行gs.execute的必要前提,必须添加。 - 拆分
-c参数:将-c作为独立数组元素,PostScript脚本单独作为下一个元素——ghostscript4js会自动处理参数传递,不需要给脚本内容额外加外层引号。 - 清理输出结果:用
trim()移除返回值中的换行、空格等空白字符,确保得到的是纯净的页数数值。 - 移除重复方法:原代码重复定义了两次
GSVersion,保留一次即可避免逻辑冲突。
验证逻辑
修改后,ghostscript4js会正确传递参数给Ghostscript,执行PostScript脚本后将页数输出到标准输出,gs.execute的then回调中就能拿到正确数值,处理后返回给Omnis即可。
内容的提问来源于stack exchange,提问作者frenchie
相关产品推荐
相关产品推荐

