Coder Social home page Coder Social logo

nicknaso / ghostscript4js Goto Github PK

View Code? Open in Web Editor NEW
66.0 6.0 19.0 374 KB

Ghostscript4JS binds the Ghostscript C API to the Node.JS world.

Home Page: http://www.nacios.it

License: Apache License 2.0

JavaScript 44.79% Python 10.51% C++ 26.85% C 17.85%
ghostscript nodejs cplusplus addon native javascript

ghostscript4js's Introduction

Ghostscript4JS

This module binds the Ghostscript C API to bring its power to the Node.JS world

Introduction

Ghostscript is a suite of software based on an interpreter for Adobe Systems' PostScript and Portable Document Format (PDF) page description languages. Its main purposes are the rasterization or rendering of such page description language files, for the display or printing of document pages, and the conversion between PostScript and PDF files.

Ghostscript can be used as a raster image processor (RIP) for raster computer printers—for instance, as an input filter of line printer daemon—or as the RIP engine behind PostScript and PDF viewers.

Ghostscript can also be used as a file format converter, such as PostScript to PDF converter. The ps2pdf conversion program, which comes with the ghostscript distribution, is described by its documentation as a "work-alike for nearly all the functionality (but not the user interface) of Adobe's Acrobat Distiller product".[3] This converter is basically a thin wrapper around ghostscript's pdfwrite output device, which supports PDF/A-1 and PDF/A-2 as well as PDF/X-3 output.[3]

Ghostscript can also serve as the back-end for PDF to raster image (png, tiff, jpeg, etc.) converter; this is often combined with a PostScript printer driver in "virtual printer" PDF creators.

As it takes the form of a language interpreter, Ghostscript can also be used as a general purpose programming environment.

Ghostscript has been ported to many operating systems, including Unix-like systems, classic Mac OS, OpenVMS, Microsoft Windows, Plan 9, MS-DOS, FreeDOS, OS/2, Atari TOS and AmigaOS.

More resource and info about Ghostscript

Motivations

At the time i created this module i was not able to find any module on npm that execute Ghostscript command through its C API, otherwise there were some module that call Ghostscript through the execution of the corresponding shell command. This is a good way to start using some library from node, but there are the following drawbacks:

  • Performance - The call to the shell command take more time and more resources than calling a library C or C++ API directly from Node.js environment.

  • Errror handler - Sometimes you cannot intercept and handle errors in a good and a proper way.

To fit all needs Ghostscript4JS has sync and async methods so it could be used in a web application where it's very important to not block the event loop, so all requests will be served without any delay originated by our application.

Understanding Node.js event loop

Prerequisites

Before installing Ghostscript4JS you need to assure you have the following prerequisites:

At moment Ghostscript4JS is fully compatible with Ghostscript from version 9.19 to 9.50

Linux

Debian systems

Install Ghostscript

apt-get install ghostscript libgs-dev

At this point you need to set the enviroment variable GS4JS_HOME to /usr/lib/x86_64-linux-gnu

Red Hat | Fedora

yum install ghostscript ghostscript-devel

At this point you need to set the enviroment variable GS4JS_HOME to /usr/lib64 or /usr/lib based on you architecture

Arch Linux

pacman -S ghostscript

At this point you need to set the enviroment variable GS4JS_HOME to /usr/lib

Alpine

apk add ghostscript

At this point you need to set the enviroment variable GS4JS_HOME to /usr/lib

In general, based on your Linux OS and architecture, you have to set the environment variable GS4JS_HOME to point on folder containing libgs.so library.

Windows

  • Download last Ghostscript version for your platform x86 or x64

  • Install Ghostscript on your system, for example in C:\gs

  • Add the environment variable GS4JS_HOME to point to a folder containing Ghostscript's DLL and Library files (Es. gsdll64.dll and gsdll64.lib). Typically, they are located in bin folder of you ghostscript installation, for example C:\gs\bin

macOS

  • Install Homebrew following the official guide here

  • Open terminal and install Ghostscript

brew install ghostscript
  • Set the environment variable GS4JS_HOME to /usr/local/lib

Official installation guide to install Ghostscript

Installation

If you want to use ghostscript4js you have to install it. There are two methods for that:

In dependencies of your package.json add the following item:

"ghostscript4js": "version"

then digit

npm install

Example:

"ghostscript4js": "*" for the latest version
"ghostscript4js": "1.0.0" for the version 1.0.0

OR

launch this command:

npm install ghostscript4js --save

Installation options

The module ghostscript4js allows you to use some installation options that you can use when in your operating system something is different against standard installation.

--GS4JS_HOME Set the GS4JS_HOME variable that represents the path in your system where is located the ghostscript library

Es. npm install ghostscript4js --GS4JS_HOME="C:/gs/bin"

--GS4JS_LIB Set the GS4JS_LIB variable that represents the file name for the ghostscript library installed in your system

Es. npm install ghostscript4js --GS4JS_LIB="libgs.so"

Only for Windows

--GS4JS_DLL Set the GS4JS_DLL variable that represents the file name for the ghostscript DLL installed in your windows system

Es. npm install ghostscript4js --GS4JS_DLL="gsdll64.dll"

Usage

'use strict'

const gs = require('ghostscript4js')

try {
  // Take decision based on Ghostscript version
  const version = gs.version()
  console.log(version)
  gs.executeSync('-sDEVICE=pngalpha -o my.png -sDEVICE=pngalpha -r144 my.pdf')
} catch (err) {
  // Handle error
  throw err
}

API

version

version() method returns an object that contains information about version of Ghostscript library installed on the system. It is important in those circumstances where you have to take decision based on different version. The returned data are similar to the example repoted below:

{
  product: "GPL Ghostscript",
  copyright: "Copyright (C) 2016 Artifex Software, Inc.  All rights reserved.",
  revision: 919,
  revisiondate: 20160323
}

This is a synchronous method and returns the version info or throws an Error to indicate that something went wrong during its execution.

Example - version

'use strict'

const gs = require('ghostscript4js')

try {
  const version = gs.version()
  console.log(version)
  // Take decision based on Ghostscript version
  if (version.revision > 916) {
    // ... some stuff
  } else {
    // ... other stuff
  }
} catch (err) {
  // Handle error
  throw err
}

executeSync

executeSync(cmd) method takes the Ghostscript command parameters in input as a string or array of strings and executes in a synchronous way. If something wrong happens in calling this method an Error with description and code error will be thrown.

Example - executeSync

'use strict'

const gs = require('ghostscript4js')

try {
  gs.executeSync('-sDEVICE=pngalpha -o my.png -sDEVICE=pngalpha -r144 my.pdf')
} catch (err) {
  // Handle error
  throw err
}

execute

execute(cmd, callback) method takes in input the Ghostscript command parameters as a string or array of strings and an optional callback. The execution will be asynchronous so this ensure better performance especially in a web application enviroment, because it'll not block the Node.Js event loop. This method has an optional callback function as input, in that case, a possible error will be handled by this function. If noone function will be provided the method returns a Promise that will be resolved or rejected as reported in the following example.

Example - execute

'use strict'

const gs = require('ghostscript4js')

let cmd = '-sDEVICE=pngalpha -o my.png -sDEVICE=pngalpha -r144 my.pdf'
gs.execute(cmd, function (err) {
  if (err) {
    console.log("Ooops... something wrong happened")
  }
})
'use strict'

const gs = require('ghostscript4js')

let cmd = '-sDEVICE=pngalpha -o my.png -sDEVICE=pngalpha -r144 my.pdf'
gs.execute(cmd)
.then(() => {
  console.log("All is ok")
})
.catch((err) => {
 console.log("Ooops... something wrong happened")
})

Error

The error raised from ghostscript4js in all of its method is an instance of Error object that cointains a message that describes what happened and at the same time cointains the Ghostscript error code so you can inspect what happened in a better way. At this link Ghostscript error codes you can find all Ghostscript errors code.

Min and Max supported revision

This module was built based on Ghostscript C API that is compatible with some specifics versions. The module has two properties MIN_SUPPORTED_REVISION and MAX_SUPPORTED_REVISION which respectively indicate the minimum and maximum supported Ghostscript's version.

Example - Min and Max supported revision

'use strict'

const gs = require('ghostscript4js')

console.log(gs.MIN_SUPPORTED_REVISION)
console.log(gs.MAX_SUPPORTED_REVISION)

Docker

Check out the example Dockerfile in examples/docker. It will create an image based on node 8.x and Debian stretch.

To build the image do:

cd examples/docker
docker build -t ghostscript4js .

Now you can run the image. By default it does npm start (which is node index.js) and exits.

docker run ghostscript4js

Running the container should output something like:

{ product: 'GPL Ghostscript',
  copyright: 'Copyright (C) 2016 Artifex Software, Inc.  All rights reserved.',
  revision: 920,
  revisiondate: 20160926 }

If you want to look around in the container you can get a shell like:

docker run -it ghostscript4js /bin/bash
gs --version

The Team

Nicola Del Gobbo

https://github.com/NickNaso/

https://www.npmjs.com/~nicknaso

https://twitter.com/NickNaso

Mauro Doganieri

https://github.com/mauro-d

https://www.npmjs.com/~mauro-d

https://twitter.com/maurodoganieri

Acknowledgements

Thank you to all people that encourage me every day.

License

Licensed under Apache license V2

ghostscript4js's People

Contributors

esemeniuc avatar george-g avatar lorenyu avatar mauro-d avatar nicknaso avatar prinzhorn avatar samb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ghostscript4js's Issues

Check command in JS env

Evaluate the possibility to check the string on the JavaScript environment and not in the C++ so the module throw an exception before to call native code.

where gs output converted file?

i can't find it anywhere?

const cmd = '-sDEVICE=pngalpha -o /usr/pdf2image/convert/file-%03d.png -r144 ' + filepath

docker-compose.yml

- '/data/db/static/pdf2image/convert:/usr/pdf2image/convert'

but it looks nothing there.

image

the output looks fine

Empty output with when using pdfwrite

Hello! Thanks for the great package, it looks promising, but something doesn't work well in my case.

I'm trying to convert a PostScript file to PDF via the following command: -sDEVICE=pdfwrite -o out.pdf -f in.ps. So, nothing fancy, all params are the default.

If I execute it in shell directly this way: gs -sDEVICE=pdfwrite -o out.pdf -f in.ps, then everything works well and the out.pdf is placed next to the in.ps.

But when I try to use the very same command with ghostscript4js, then I get no PDF file and no error.
Here is the code I use:

const gs = require('ghostscript4js');
let cmd = '-sDEVICE=pdfwrite -o out.pdf -f in.ps';
try {
    gs.executeSync(cmd);
} catch (err) {
    console.log('Err');
}

And here is the console output:

ghost node index.js
GPL Ghostscript 9.21 (2017-03-16)
Copyright (C) 2017 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
%%BoundingBox: 89 39 523 683
%%HiResBoundingBox: 89.981997 39.095999 522.503984 682.073979
%%BoundingBox: 90 43 523 681
%%HiResBoundingBox: 90.215997 43.415999 522.503984 680.147979

I tried the sample code with the PNG file from the readme and it works well. It seems to be something specific with the pdfwrite. If you have any suggestions I'd much appreciate it! Thanks!

Here is some info about my environment:

OS: macOS 10.12.6
Node: v8.4.0 (I also tried with node v6)
Ghostscript: 9.21
Sample PostScript file I used: link (I also tried a bunch of other ps files, but no luck)

Is it possible to pass a stream and receive a stream?

Current API seems to allow only for using filesystem for I/O. I am currently spawning GS with child_process.spawn and piping files in & out, like in:
gs -q -sstdout=/dev/null -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=- -c .setpdfwrite -

¿Is there a way to use streaming?

thnx!

Error during npm installation

I have installed the 32-bit version of GH 9.20 and registered C:\Program Files (x86)\gs\gs9.20\bin as GS4JS_HOME but the npm package fails to install, seemingly requiring the 64-bit files?


C:\dev\pss2-backend>npm i

> [email protected] install C:\dev\pss2-backend\node_modules\ghostscript4js
> node-gyp rebuild


C:\dev\pss2-backend\node_modules\ghostscript4js>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild ) 
Warning: Missing input files:
C:\gs\bin\gsdll64.dll        
C:\gs\bin\gsdll64.lib        
Building the projects in this solution one at a time. To enable parallel build, please add the "-m" switch.
  nothing.c
  win_delay_load_hook.cc
  nothing.vcxproj -> C:\dev\pss2-backend\node_modules\ghostscript4js\build\Release\\nothing.lib
  Copying C:/gs/bin/gsdll64.dll to C:\dev\pss2-backend\node_modules\ghostscript4js/build/Release\gsdll64.dll
  The system cannot find the path specified.
  Copying C:/gs/bin/gsdll64.lib to C:\dev\pss2-backend\node_modules\ghostscript4js/build/Release\gsdll64.lib
  The system cannot find the path specified.
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\Microsoft.CppCommon.targets(231,5): warning M 
SB8064: Custom build for item "C:\gs\bin\gsdll64.dll" succeeded, but specified dependency "c:\gs\bin\gsdll64.dll" does not exist. Thi 
s may cause incremental build to work incorrectly. [C:\dev\pss2-backend\node_modules\ghostscript4js\build\ghostscript4js.vcxproj]     
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\Microsoft.CppCommon.targets(231,5): warning M 
SB8065: Custom build for item "C:\gs\bin\gsdll64.dll" succeeded, but specified output "c:\dev\pss2-backend\node_modules\ghostscript4j 
s\build\release\gsdll64.dll" has not been created. This may cause incremental build to work incorrectly. [C:\dev\pss2-backend\node_mo 
dules\ghostscript4js\build\ghostscript4js.vcxproj]
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\Microsoft.CppCommon.targets(231,5): warning M 
SB8064: Custom build for item "C:\gs\bin\gsdll64.lib" succeeded, but specified dependency "c:\gs\bin\gsdll64.lib" does not exist. Thi 
s may cause incremental build to work incorrectly. [C:\dev\pss2-backend\node_modules\ghostscript4js\build\ghostscript4js.vcxproj]     
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\Microsoft.CppCommon.targets(231,5): warning M 
SB8065: Custom build for item "C:\gs\bin\gsdll64.lib" succeeded, but specified output "c:\dev\pss2-backend\node_modules\ghostscript4j 
s\build\release\gsdll64.lib" has not been created. This may cause incremental build to work incorrectly. [C:\dev\pss2-backend\node_mo 
dules\ghostscript4js\build\ghostscript4js.vcxproj]
  ghostscript4js.cc
  win_delay_load_hook.cc
LINK : fatal error LNK1104: cannot open file 'C:\dev\pss2-backend\node_modules\ghostscript4js\build\Release\gsdll64.lib' [C:\dev\pss2 
-backend\node_modules\ghostscript4js\build\ghostscript4js.vcxproj]
gyp ERR! build error 
gyp ERR! stack Error: `C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\MSBuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:194:23)        
gyp ERR! stack     at ChildProcess.emit (events.js:311:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Windows_NT 10.0.18363
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\dev\pss2-backend\node_modules\ghostscript4js
gyp ERR! node -v v12.16.1
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\a\AppData\Roaming\npm-cache\_logs\2020-08-10T08_57_37_486Z-debug.log

C:\dev\pss2-backend>

Release 3.2.0

The release 3.2.0 will contains updates to solve the following issues:

  • Segmentation fault on multiple runs - Fix issue #47
  • Execution stop with: double free or corruption - Fix issue #49
  • Error when calling gs.executeSync - Fix issue #50

ghostscript4js and docker compatibility

This is my docker file :

FROM ubuntu:latest

RUN apt-get update
RUN apt -y install curl
RUN curl -sL https://deb.nodesource.com/setup_8.x | bash -
RUN apt-get -y install nodejs
RUN apt-get -y install make
RUN apt-get -y install sudo
RUN sudo apt-get -y install ghostscript
RUN sudo apt-get -y install libgs-dev

VOLUME ["/data"]

ADD . /data
RUN cd /data && npm install

EXPOSE 8080

WORKDIR /data

CMD ["npm", "start"]

I got this message when i launch the container.

node dist

/data/node_modules/bindings/bindings.js:88
throw e
^

Error: /data/node_modules/ghostscript4js/build/Release/ghostscript4js.node: invalid ELF header
at Object.Module._extensions..node (module.js:664:18)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at bindings (/data/node_modules/bindings/bindings.js:81:44)
at Object. (/data/node_modules/ghostscript4js/lib/ghostscript4js.js:25:31)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)

I try the install in a clean Ubuntu VM and i didnt get this message. It works well.

Create executeSync method

Create the executeSync method that have the responsability to parse and execute the ghostscript command.

function executeSync(GhostscriptCommand) {}

It's necessary to implement the Javascript and C++ binding for the method.

Use Nan:ThrowError to dispatch errors.

GS error not caught by js code

I am trying to handle a GS font error gracefully. So I tried ghostscript4js. WHen I ran it on a document that i know has a font issue, this was not handled by the library. Here is the output for reference. I am using the example provided on the readme using the callback. It just prints 'All is OK'

(node:2270) Warning: N-API is an experimental feature and could change at any time.
GPL Ghostscript 9.26 (2018-11-20)
Copyright (C) 2018 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
Can't find CID font "Calibri".
Attempting to substitute CID font /Adobe-Identity for /Calibri, see doc/Use.htm#CIDFontSubstitution.
The substitute CID font "Adobe-Identity" is not provided either. attempting to use fallback CIDFont.See doc/Use.htm#CIDFontSubstitution.
The fallback CID font "CIDFallBack" is not provided. Finally attempting to use ArtifexBullet.
**** Error reading a content stream. The page may be incomplete.
Output may be incorrect.
**** Error: File did not complete the page properly and may be damaged.
Output may be incorrect.
%%BoundingBox: 17 17 1203 771
%%HiResBoundingBox: 17.421875 17.097656 1202.404297 770.152344
All is ok
root@948c20816c14:/docs#

Ghostscript 9.22

Check if the addon is compatible with the new version of Ghostscript and update the maximum version on the code and on the documentation

.execute()\.executeSync() functions are ignoring the first parameter

Hi there!
I'm trying to execute gs with the following properties -r500 -dNOPAUSE -sDEVICE=png16m -dBATCH -o <path> <path> and I constantly getting a low resolution images. After a couple of hours, I figure out that .execute() function ignoring the first parameter (in that case -r500). I've changed the order to the following -dNOPAUSE -r500 -sDEVICE=png16m -dBATCH -o <path> <path> and the images resolution was fine.
As I see in docs we have a double call of -sDevice gs.executeSync('-sDEVICE=pngalpha -o my.png -sDEVICE=pngalpha -r144 my.pdf') and that part doesn't make any sense for me either. Why we have a double -sDevice call?
Is that a feature or a bug? Could someone please explain it to me?
Thank you.

Invalid file path

When building on windows i found that the file:
g4js-home.js
should be named
gs4js-env-home.js

see the binding file snippet below:
['OS=="win"', { "conditions": [ ['target_arch=="x64"', { "variables": { "GS4JS_HOME%": "<!(node gs4js-env-home.js)", "GS4JS_LIB%": "gsdll64.lib", "GS4JS_DLL%": "gsdll64.dll", "conditions": [ ['"<!(node gs4js-env-home.js)" == ""', { "GS4JS_HOME%": "C:/gs/bin" }] ] } }, { "variables": { "GS4JS_HOME%": "<!(node gs4js-env-home.js)", "GS4JS_LIB%": "gsdll32.lib", "GS4JS_DLL%": "gsdll32.dll", "conditions": [ ['"<!(node gs4js-env-home.js)" == ""', { "GS4JS_HOME%": "C:/gs/bin" }] ] } }] ],

N-API porting of ghostscript4js

I think that we can start to port ghostscript4js to N-API and after that go forward to add the new requested features that end user requested us.
I will provide to create a new branch node-addon-api to start the porting.

Can't install ghostscript4js. Crash on node-gyp rebuild

Hi,
After deleting my node_modules and updating some packages i have some trouble re-installing ghostscript4js.
When i do npm install
i have this result :

npm install --python=python2.7

> [email protected] install /Users/me/Documents/Projets/my_project/node_modules/ghostscript4js
> node-gyp rebuild

gyp WARN download NVM_NODEJS_ORG_MIRROR is deprecated and will be removed in node-gyp v4, please use NODEJS_ORG_MIRROR
gyp WARN download NVM_NODEJS_ORG_MIRROR is deprecated and will be removed in node-gyp v4, please use NODEJS_ORG_MIRROR
gyp WARN download NVM_NODEJS_ORG_MIRROR is deprecated and will be removed in node-gyp v4, please use NODEJS_ORG_MIRROR
  CC(target) Release/obj.target/nothing/../node-addon-api/src/nothing.o
  LIBTOOL-STATIC Release/nothing.a
Traceback (most recent call last):
  File "./gyp-mac-tool", line 611, in <module>
    sys.exit(main(sys.argv[1:]))
  File "./gyp-mac-tool", line 28, in main
    exit_code = executor.Dispatch(args)
  File "./gyp-mac-tool", line 43, in Dispatch
    return getattr(self, method)(*args[1:])
  File "./gyp-mac-tool", line 246, in ExecFilterLibtool
    if not libtool_re.match(line) and not libtool_re5.match(line):
TypeError: cannot use a string pattern on a bytes-like object
make: *** [Release/nothing.a] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/me/.nvm/versions/node/v8.12.0/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at emitTwo (events.js:126:13)
gyp ERR! stack     at ChildProcess.emit (events.js:214:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
gyp ERR! System Darwin 18.0.0
gyp ERR! command "/Users/me/.nvm/versions/node/v8.12.0/bin/node" "/Users/me/.nvm/versions/node/v8.12.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/me/Documents/Projets/my_project/node_modules/ghostscript4js
gyp ERR! node -v v8.12.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN [email protected] requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of webpack@^3.0.0 || ^4.0.0-alpha.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of webpack@^3.0.0 || ^4.0.0-alpha.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/me/.npm/_logs/2018-10-17T14_44_42_981Z-debug.log

-dNOPAUSE not working

Even if i pass this flag, my program still waits for the key to be pressed. Did someone have the same problem?

Warning on Microsoft compiler

Microsoft compiler give a warning:
..\src\ghostscript4js.cc(166): warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc [C:\Users\nicknaso\Desktop\prova\node_modules\ghostscript4js\bui ld\ghostscript4js.vcxproj]
Need to investigate and fix the warning.

undefinedfilename error on Windows if file path contains spaces

Let's assume we have these input and output file paths:

const output = "C:\\Users\\letalumil\\Test folder\\node-love-ghostscript.png";
const input = "C:\\Users\\letalumil\\Test folder\\node-love-ghostscript.pdf";

And we try to convert the pdf this way:

const cmd = `-sDEVICE=pngalpha -o ${output} -sDEVICE=pngalpha -r144 ${input}`;

Or that way (quotes around the paths):

const cmd = `-sDEVICE=pngalpha -o "${output}" -sDEVICE=pngalpha -r144 "${input}"`;

In boths cases the operation fails with corresponding errors:

GPL Ghostscript 9.21 (2017-03-16)
Copyright (C) 2017 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Error: /undefinedfilename in (folder\\node-love-ghostscript.png)
Operand stack:
Execution stack:
%interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push
 Dictionary stack:
--dict:1201/1684(
GPL Ghostscript 9.21: Unrecoverable error, exit code 1
ro)(G)--   --dict:0/20(G)--   --dict:78/200(L)--
Current allocation mode is local
Last OS error: No such file or directory

And

GPL Ghostscript 9.21 (2017-03-16)
Copyright (C) 2017 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Error: /undefinedfilename in (folder\\node-love-ghostscript.png")
Operand stack:
Execution stack:
%interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --n
ostringval--   --nostringval--   --nostringval--   false   1   %stopped_push
Dictionary stack:
--dict:1201/1684(
GPL Ghostscript 9.21: Unrecoverable error, exit code 1
ro)(G)--   --dict:0/20(G)--   --dict:78/200(L)--
Current allocation mode is local
Last OS error: No such file or directory

If I remove the space in the Test folder name and run the command without quotes around paths, then everything works. If The folder is renamed, but the quotes are still there, then I get a similar error:

GPL Ghostscript 9.21 (2017-03-16)
Copyright (C) 2017 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Error: /undefinedfilename
GPL Ghostscript 9.21: Unrecoverable error, exit code 1
in ("C:\\Users\\letalumil\\Test_folder\\node-love-ghostscript.pdf")
Operand stack:
Execution stack:
%interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --n
ostringval--   --nostringval--   --nostringval--   false   1   %stopped_push
Dictionary stack:
 --dict:1204/1684(ro)(G)--   --dict:0/20(G)--   --dict:78/200(L)--
Current allocation mode is local
Last OS error: Invalid argument

firebase nodejs: /usr/lib/x86_64-linux-gnu/libgs.so: No such file or directory

Hi,

I'm getting this error when I try to deploy to firebase nodejs - any input on what I'm missing is much appreciated:

Deployment error.
Build failed: 
{
  "error": {
    "canonicalCode": "INVALID_ARGUMENT",
    "errorMessage": "`npm_install` had stderr output:
    node-pre-gyp WARN 
    Using request for node-pre-gyp https download 
    g++: error: /usr/lib/x86_64-linux-gnu/libgs.so: No such file or directory
    make: *** [Release/obj.target/ghostscript4js.node] Error 1
    gyp ERR! build error 
    gyp ERR! stack Error: `make` failed with exit code: 2
    gyp ERR! stack     at ChildProcess.onExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:262:23)
    gyp ERR! stack     at emitTwo (events.js:126:13)
    gyp ERR! stack     at ChildProcess.emit (events.js:214:7)
    gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
    gyp ERR! System Linux 4.15.0-1044-gcp
    gyp ERR! command \"/usr/bin/node\" \"/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js\" \"rebuild\"
    gyp ERR! cwd /workspace/node_modules/ghostscript4js
    gyp ERR! node -v v8.16.0
    gyp ERR! node-gyp -v v3.8.0
    gyp ERR! not ok 
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! [email protected] install: `node-gyp rebuild`
    npm ERR! Exit status 1
    npm ERR! 
    npm ERR! Failed at the [email protected] install script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR!     /builder/home/.npm/_logs/2020-03-09T10_06_18_268Z-debug.log
    error: `npm_install` returned code: 1",
    "errorType": "InternalError",
    "errorId": "F8BCC123"
  }
}

I was trying to override --GS4JS_HOME but then it fails during the npm install ghostscript-js.

GS4JS_LIB variable isn't used

I'm installing into a docker image.

The installation of ghostscript does not have a 'libgs.so', it has:

root@c1a8e5e5f9f6:/usr/bin# find / -name libgs.so*
/usr/lib/libgs.so.9
/usr/lib/libgs.so.9.06

I tried overriding it but it did not work:

--GS4JS_LIB="libgs.so.9"

Looking at the code in binding.gyp, line 15, it is hard-coded, and not respecting the parameter provided.
It should look like:

        ['OS=="linux"', {
          'variables': {
            "GS4JS_HOME%": "<!(echo $GS4JS_HOME)",
            "GS4JS_LIB%": "<!(echo $GS4JS_LIB)",
            "conditions": [
              ['"<!(echo $GS4JS_HOME)" == ""', {
                "GS4JS_HOME%": "/usr/lib/x86_64-linux-gnu"
              }],
              ['"<!(echo $GS4JS_LIB)" == ""', {
                "GS4JS_LIB%": "libgs.so"
              }]
            ]
          },
          "libraries": ["<(GS4JS_HOME)/<(GS4JS_LIB)"]
        }],

Problem calling execute method multiple time consecutively

The module raise a problem calling async execute method multiple times as reported below:

let cmd = '-sDEVICE=pngalpha -o my1.png -sDEVICE=pngalpha -r144 my.pdf'
let cmd2 = '-sDEVICE=pngalpha -o my2.png -sDEVICE=pngalpha -r144 my.pdf'
gs.execute(cmd, function (err) {
  if (err) {
    console.log("Ooops... something wrong happened")
  }
})
gs.execute(cmd2, function (err) {
  if (err) {
    console.log("Ooops... something wrong happened")
  }
})

Empty output file

export async function compressPdf(data: Buffer): Promise<Buffer> {
    const fileHash = md5(data);
    const inFile = `${fileHash}.pdf`;
    const outFile = `${fileHash}_compressed.pdf`;
    const cmd = `-sDEVICE=pdfwrite -dPDFSETTINGS=/screen -dCompatibilityLevel=1.4 -dNOPAUSE -dQUIET -dBATCH -o ${outFile} ${inFile}`;
    await fs.writeFile(inFile, data);
    await fs.open(outFile, 'w').then(fd => fd.close());
    await gs.execute(cmd);
    return fs.readFile(outFile);
}

This script gives me empty output file. If I don't create it using fs.open I receive an error: [Error: ENOENT: no such file or directory

Improvements

Start on experiment to solve all issues and improve performance and functionalities

  • Try to share the instance of Ghostscript and avoid to initialise and destroy every time. Try to use object wrap api to accomplish this.
  • Use the Node.js stream API to pass the data to process to Ghostscript. Investigate if this could cause problem in particular with the asynchronous api
  • Improve error handling
  • Improve command line parser
  • Use prebuildify to generate the binary for the system
  • Improve the unit tests
  • Add all on CI

Suppress console output

Is there a way to suppress the console output of ghostscript?
When I convert a pdf to jpg like this:

const gs = require('ghostscript4js');
const command = `-r300 -sPAPERSIZE=a4 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dUseTrimBox -sDEVICE=jpeg -dDownScaleFactor=3 -o out-%d.jpg -dJPEGQ=100 -f in.pdf`;
await gs.execute(command);

I get this output in the console:

GPL Ghostscript 9.21 (2017-03-16)
Copyright (C) 2017 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 2.
Page 1
Page 2

When I use the gs command directly, I usually just add the "-q" flag.

execution stop with: double free or corruption (fasttop)

Hi nick,

I try to run the execute with tiffsep and sometimes it works and sometimes I get an error: double free or corruption (fasttop)

const gs = require('ghostscript4js')

;(async function() {

await gs.execute(`-dBATCH -dNOPAUSE -dSAFER -sDEVICE=tiffsep -dFirstPage=1 -dLastPage=1 -r265 -sOutputFile=output.tif input.pdf`)
})()

Unfortunately when this happens the package only shows the error in the console but I'm not able to intercept it in a try-catch.

I'm running Node 8.16.2 on Fedora 31
GPL Ghostscript 9.27 (2019-04-04)
"ghostscript4js": "^3.1.1",

Create execute method

Create the execute method that has the responsability to parse and execute the ghostscript command in asynchrnous way.

function execute(GhostscriptCommend, callback) {}

It's necessary to implement the Javascript and C++ binding for the method.

Use Nan:ThrowError to dispatch errors.

spot color layer completely black using tiffsep

Hi @NickNaso

thank you for this awesome work, it is really useful, but i had a problem that i guess is a bug.

When I try to use the tiffsep sDevice option some of the layers that are spot color are generated completely black.

I don't know the cause but if I try to run the same command in the shell it works.

// Run ghostscript
try {
	gs.executeSync('-dBATCH -dNOPAUSE -dSAFER -sDEVICE=tiffsep -dFirstPage=1 -dLastPage=1 -r144 -sOutputFile=output.tif "./input.pdf"')
} catch (err) {
	// Handle error
	console.error('gs =>', err)
}

Support For firebase functions ?

@NickNaso Hey brother,

This library can be really usefull for firebase and aws lambada users.
I am using firebase and the available options for gs is not updated for a while (like available gs version is best at 9.2)
See this Ghostscript Firebase Functions on stackoverflow as with available library using -c (postscript command) is not possible for a reason.

Pleaee modify the installation process of GS4JS for firebase functions, like node-gs is doing, looking for executable(portable to be uploaded) in folder

It would be really great.
Waiting for your positive response brother :)

Segmentation fault on multiple runs

OS: macOS 10.14.5
Node version: 10.15.3
Ghostscript version: 9.27 (2019-04-04)
Electron version: 5.0.7
Ghostscript4js version: 3.1.1

I am converting postscript files to text files using the following:

gs.executeSync("-sDEVICE=txtwrite -dNOPAUSE -dQUIET -dBATCH \
    -sOutputFile=output.txt -sDEVICE=txtwrite input.ps");

It works the first time but my electron application crashes when I try to convert a second file.

The command runs fine on bash but gives a segmentation fault when I run it on Node REPL:

> const gs = require("ghostscript4js")
undefined
> gs.executeSync("-sDEVICE=txtwrite -dNOPAUSE -dQUIET -dBATCH -sOutputFile=job1.txt -sDEVICE=txtwrite job-1.ps")
undefined
> gs.executeSync("-sDEVICE=txtwrite -dNOPAUSE -dQUIET -dBATCH -sOutputFile=job2.txt -sDEVICE=txtwrite job-1.ps")
[1]    70491 segmentation fault  node

Note job2.txt was not created and it crashed after with a segmentation fault.

Conversion to PDF/A fails without error message

I need to convert a pdf to pdf/a.

Therefore I tried to execute GS with the following script:

const gs = require('ghostscript4js')

try {
    gs.executeSync('-dPDFA -dBATCH -dNOPAUSE -dUseCIEColor -sProcessColorModel=DeviceCMYK -sDEVICE=pdfwrite -sPDFACompatibilityPolicy=1 -sOutputFile=my-pdfa.pdf my-pdf.pdf')
} catch (err) {
    throw err
}

this creates the file my-pdf-a.pdf, but it is actually not converted to PDF/A.

If I run the exact same command on the same input pdf on the shell like
gs -dPDFA -dBATCH -dNOPAUSE -dUseCIEColor -sProcessColorModel=DeviceCMYK -sDEVICE=pdfwrite -sPDFACompatibilityPolicy=1 -sOutputFile=my-pdfa.pdf my-pdf.pdf

it correctly outputs the file my-pdfa.pdfas PDF/A.

Performance tests

To implement comparison tests to show performace differences between other solutions.

Install on MacOS 10.14.6 fails with

Install on MacOS 10.14.6 fails. I have tried reinstalling ghostscript, installed node-gyp, Mac OSX developertools, but I can't get it to work. Any suggestions would be welcome....

npm install ghostscript4js fails with the following errors

> node-gyp rebuild

  CC(target) Release/obj.target/nothing/../node-addon-api/src/nothing.o
  LIBTOOL-STATIC Release/nothing.a
Traceback (most recent call last):
  File "./gyp-mac-tool", line 611, in <module>
    sys.exit(main(sys.argv[1:]))
  File "./gyp-mac-tool", line 30, in main
    exit_code = executor.Dispatch(args)
  File "./gyp-mac-tool", line 45, in Dispatch
    return getattr(self, method)(*args[1:])
  File "./gyp-mac-tool", line 248, in ExecFilterLibtool
    if not libtool_re.match(line) and not libtool_re5.match(line):
TypeError: cannot use a string pattern on a bytes-like object
make: *** [Release/nothing.a] Error 1
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/Oscar/.nvm/versions/node/v11.2.0/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (events.js:182:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:254:12)
gyp ERR! System Darwin 18.7.0
gyp ERR! command "/Users/tvr/.nvm/versions/node/v11.2.0/bin/node" "/Users/tvr/.nvm/versions/node/v11.2.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/tvr/loopback/KAM-pdf-viewer/pdfserver/node_modules/ghostscript4js
gyp ERR! node -v v11.2.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok 
npm WARN [email protected] requires a peer of vue@^2.0.0 but none is installed. You must install peer dependencies yourself.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Issue with the new update [email protected]

Hi, I tried to run npm update today and when running the update of ghostscript4js I have this issue:

Error: Cannot find module 'C:\Tools\EB\back\node_modules\ghostscript4js\gs4js-env-dll.js'
...
gyp: Call to 'node gs4js-env-dll.js' returned exit status 1 while in binding.gyp. while trying to load binding.gyp

Anyone encountered this issue?
Thanks for any helps!
Regards
D.

I posted before on the ghostscriptjs issue forum and thanks rmeja to remind me! Sorry for that

Create version method

Create the version method that have the responsability to check the actual version of ghostscript. It's important to be sure that the correct version of the ghostsctipt library is loaded.

Base the code as in the reference manual:

typedef struct gsapi_revision_s {
    const char *product;
    const char *copyright;
    long revision;
    long revisiondate;
} gsapi_revision_t;
gsapi_revision_t r;

if (gsapi_revision(&r, sizeof(r)) == 0) {
    if (r.revision < 650)
       printf("Need at least Ghostscript 6.50");
}
else {
    printf("revision structure size is incorrect");
}

node-gyp rebuild failed

osx
brew install ghostscript
node 8.16

GS4JS_HOME=/usr/local/lib

node-gyp rebuild

  CC(target) Release/obj.target/nothing/../node-addon-api/src/nothing.o
  LIBTOOL-STATIC Release/nothing.a
  CXX(target) Release/obj.target/ghostscript4js/src/ghostscript4js.o
  SOLINK_MODULE(target) Release/ghostscript4js.node
clang: error: no such file or directory: '/usr/local/lib/libgs.dylib'

Problem starting test on windows

An error issued trying to start test suite from Windows OS
Error: node_modules is not comand ...
On Linux and macOS this problem never happened.

symbol lookup error: gsapi_set_arg_encoding

I can npm install fine with npm install ghostscript4js --GS4JS_HOME="/usr/lib" however when try to actually execute GS I get the following error.

This is on Debian using Docker.

node: symbol lookup error: /usr/lib/node_modules/ghostscript4js/build/Release/ghostscript4js.node: undefined symbol: gsapi_set_arg_encoding

root@eaf7e6871672:/usr/lib# ls -la | grep libgs
-rw-r--r-- 1 root root 13983398 Apr 28 09:42 libgs.a
lrwxrwxrwx 1 root root       13 Apr 28 09:42 libgs.so -> libgs.so.9.06
lrwxrwxrwx 1 root root       13 Apr 28 09:42 libgs.so.9 -> libgs.so.9.06
-rw-r--r-- 1 root root 10453152 Apr 28 09:42 libgs.so.9.06

Libraries are there and I installed everything using apt-get -y install libgs-dev ghostscript

Thanks!

Compilation error

To use the Ghostscript C API you need to compile with lgs options as reported below:

g++ -o output-file source-file -lgs

Please refer to this example to successfully compile for different platform:

Error when calling gs.executeSync

(index):125 Uncaught Error: Sorry error happened executing Ghostscript command. Error code: -100
at Object.executeSync (E:\Adstream\ReactElectronApp\QPPElectron\qpp\node_modules\ghostscript4js\lib\ghostscript4js.js:56)
at EventEmitter.ipcRenderer.on ((index):119)
at EventEmitter.emit (events.js:182)

ipcRenderer.on('convert-pdf', (evt, args) => {
        try {
          const version = gs.version();
          console.log(version);
          gs.executeSync(
            `-sDEVICE=pngalpha -o my.png -sDEVICE=pngalpha -r144 ${args}`
          );
        } catch (err) {
          throw err;
        }
      });

args: path of pdf file

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.