Coder Social home page Coder Social logo

yakovmeister / pdf2image Goto Github PK

View Code? Open in Web Editor NEW
376.0 7.0 135.0 44.21 MB

A utility for converting pdf to image and base64 format.

License: MIT License

JavaScript 1.34% TypeScript 98.47% Shell 0.18%
pdf-to-image pdf graphicsmagick node-pdf node-pdf-to-image node-pdf2img

pdf2image's Introduction

pdf2pic

Donate Build Status CodeFactor Maintainability Test Coverage install size NPM Version License Known Vulnerabilities Downloads Stats

A utility for converting pdf to image, base64 or buffer format.

IMPORTANT NOTE: Please support this library by donating via PayPal, your help is much appreciated. Contributors are also welcome!

Prerequisites

  • node >= 14.x
  • graphicsmagick
  • ghostscript

Don't have graphicsmagick and ghostscript yet?

Follow this guide to install the required dependencies.

Installation

npm install --save pdf2pic

Usage

Converting specific page of PDF from path, then saving as image file

import { fromPath } from "pdf2pic";

const options = {
  density: 100,
  saveFilename: "untitled",
  savePath: "./images",
  format: "png",
  width: 600,
  height: 600
};
const convert = fromPath("/path/to/pdf/sample.pdf", options);
const pageToConvertAsImage = 1;

convert(pageToConvertAsImage, { responseType: "image" })
  .then((resolve) => {
    console.log("Page 1 is now converted as image");

    return resolve;
  });

Nuff talk, show me how:

More usage example can be found here.

pdf2pic API

fromPath(filePath, options)

Initialize PDF to image conversion by supplying a file path

Functions

Convert a specific page of the PDF to Image/Base64/Buffer by supplying a file path

fromPath(filePath, options)(page, convertOptions)
  • filePath - pdf file's path
  • options - see options.
  • page - page number to convert to an image
  • convertOptions - see convertOptions.

Converts PDF to Image/Base64/Buffer by supplying a file path

fromPath(filePath, options).bulk(pages, convertOptions)
  • filePath - pdf file's path
  • options - see options.
  • pages - page numbers to convert to image
    • set pages to -1 to convert all pages
    • pages also accepts an array indicating the page number e.g. [1,2,3]
    • also accepts number e.g. 1
  • convertOptions - see convertOptions

Set GraphicsMagick's subclass or path

fromPath(filePath, options).setGMClass(subClass)

NOTE: should be called before calling convert() or bulk().

  • filePath - pdf file's path
  • options - see options.
  • subClass - path to gm binary or set to true to use imagemagick
    • set subClass to true to use imagemagick
    • supply a valid path as subClass to locate gm path specified

fromBuffer(buffer, options)

Initialize PDF to image conversion by supplying a PDF buffer

Functions

Convert a specific page of the PDF to Image/Base64/Buffer by supplying a buffer

fromBuffer(buffer, options)(page, convertOptions)

Functions same as fromPath(filePath, options)(page, convertOptions) only input is changed


Converts PDF to Image/Base64/Buffer by supplying a buffer:

fromBuffer(buffer, options).bulk(pages, convertOptions)

Functions same as fromPath(filePath, options).bulk(pages, convertOptions) only input is changed


Set GraphicsMagick's subclass or path:

fromBuffer(buffer, options).setGMClass(subClass)

Functions same as fromPath(filePath, options).setGMClass(subClass) only input is changed


fromBase64(b64string, options)

Initialize PDF to image conversion by supplying a PDF base64 string.

Functions

Convert a specific page of the PDF to Image/Base64/Buffer by supplying a base64 string:

fromBase64(b64string, options)(page, convertOptions)

Functions same as fromPath(filePath, options)(page, convertOptions) only input is changed.


Converts PDF to Image/Base64/Buffer by supplying a base64 string:

fromBase64(b64string, options).bulk(pages, convertOptions)

Functions same as fromPath(filePath, options).bulk(pages, convertOptions) only input is changed.


Set GraphicsMagick's subclass or path:

fromBase64(b64string, options).setGMClass(subClass)

Functions same as fromPath(filePath, options).setGMClass(subClass) only input is changed.

options

Following are the options that can be passed on the pdf2pic api:

option default value description
quality 0 Image compression level. Value depends on format, usually from 0 to 100 (more info)
format 'png' Formatted image characteristics / image format (image characteristics, image format)
width 768 Output width
height 512 Output height
preserveAspectRatio false Maintains the aspect ratio of the image. When set to true and both width and height are specified, they are interpreted as the minimum width and minimum height, respectively. If set to true with only the width specified, the height will be automatically determined while preserving the aspect ratio, and vice versa.
density 72 Output DPI (dots per inch) (more info)
savePath './' Path where to save the output
saveFilename 'untitled' Output filename
compression 'jpeg' Compression method (more info)

convertOptions

option default value description
responseType image Response type of the output. Accepts: image, base64 or buffer

The parameter can also be a boolean, if true then the response type will be base64 and if false then the response type will be image. This is deprecated and will be removed in the next major version.

Contributing

  • Fork it (https://github.com/yakovmeister/pdf2image/fork)
  • Create your feature branch (git checkout -b feature/make-maintainer-cry)
  • Commit your changes (git commit -am 'feature: make maintainer cry by running git rm -rf')
  • Push to the branch (git push origin feature/make-maintainer-cry)
  • Create a new PR

License

pdf2pic is MIT licensed.

pdf2image's People

Contributors

amauryliet avatar clauzzz avatar dependabot-preview[bot] avatar dependabot[bot] avatar ftorto avatar greenkeeper[bot] avatar guillaumegarcia13 avatar hadrien-f avatar javi avatar marcesengel avatar mjunix avatar mrichtsfeld avatar mskec avatar nomoreviolence avatar sdg9670 avatar sebikeller avatar yakovmeister avatar yhanwen 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  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  avatar

pdf2image's Issues

Filenames with square brackets cause write failure

The module functions as expected until a source file with square brackets in the filename is provided for conversion. This results in an error in creating the image from the pdf page. AFAIK, spaces and other allowable characters are fine; will do more thorough dive soon.

Problem with Typescript declaration

When I try to build this I got an error:

node_modules/pdf2pic/dist/index.d.ts(2,25): error TS2307: Cannot find module '@module/types/convert' or its corresponding type declarations.
node_modules/pdf2pic/dist/types/convert.d.ts(1,36): error TS2307: Cannot find module '@module/types/writeImageResponse' or its corresponding type declarations.
node_modules/pdf2pic/dist/types/convert.d.ts(2,34): error TS2307: Cannot find module '@module/types/toBase64Response' or its corresponding type declarations.

---Edit:
Temporarily I solved this issue by adding to compilerOptions property: "skipLibCheck": true

TypeError: PDF2Pic is not a constructor

Hi everyone,
I'm trying to use pdf2pic as the example :

let PDF2Pic = require('pdf2pic').default
let converter = new PDF2Pic({
  density: 100,           // output pixels per inch
  savename: "untitled",   // output file name
  savedir: "./images",    // output file location
  format: "png",          // output file format
  size: 600               // output size in pixels
})

// by default the first page of the pdf will be converted
// to image
converter.convert("/path/to/pdf/sample.pdf")
  .then(resolve => {
    console.log("image converted successfully")
  })

But it returns the following error :

/mnt/c/Users/totorelmatador/Desktop/test/test.js:3
let converter = new PDF2Pic({
                ^

TypeError: PDF2Pic is not a constructor
    at Object.<anonymous> (/mnt/c/Users/totorelmatador/Desktop/test/test.js:3:17)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3

I do not understand what is the source of the problem... I tried to remove the .defaut from the require as follow :

let PDF2Pic = require('pdf2pic')

But I obtain this error :

(node:2145) UnhandledPromiseRejectionWarning: Error: Could not execute GraphicsMagick/ImageMagick: gm "identify" "-ping" "-format" "%p" "./extracted.pdf" this most likely means the gm/convert binaries can't be found
    at ChildProcess.<anonymous> (/mnt/c/Users/totorelmatador/Desktop/test/node_modules/gm/lib/command.js:232:12)
    at emitOne (events.js:116:13)
    at ChildProcess.emit (events.js:211:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:196:12)
    at onErrorNT (internal/child_process.js:372:16)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
    at Function.Module.runMain (module.js:695:11)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3
(node:2145) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2145) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:2145) UnhandledPromiseRejectionWarning: Error: Could not execute GraphicsMagick/ImageMagick: gm "convert" "-density" "100x100" "-quality" "75" "-[0]" "-resize" "600x" "-compress" "jpeg" "./tattoo_process/untitled_1.png" this most likely means the gm/convert binaries can't be found
    at ChildProcess.<anonymous> (/mnt/c/Users/totorelmatador/Desktop/test/node_modules/gm/lib/command.js:232:12)
    at emitOne (events.js:116:13)
    at ChildProcess.emit (events.js:211:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:196:12)
    at onErrorNT (internal/child_process.js:372:16)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
    at Function.Module.runMain (module.js:695:11)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3
(node:2145) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Can someone help me ? :D
Thank you !

UnhandledPromiseRejectionWarning

(node:53784) UnhandledPromiseRejectionWarning: Error: write EPIPE
at afterWriteDispatched (internal/stream_base_commons.js:154:25)
at writeGeneric (internal/stream_base_commons.js:145:3)
at Socket._writeGeneric (net.js:784:11)
at Socket._write (net.js:796:8)
at doWrite (_stream_writable.js:403:12)
at writeOrBuffer (_stream_writable.js:387:5)
at Socket.Writable.write (_stream_writable.js:318:11)
at ReadStream.ondata (_stream_readable.js:695:22)
at ReadStream.emit (events.js:310:20)
at ReadStream.Readable.read (_stream_readable.js:493:10)

Installing on Aws ElasticBeanstalk

Hi !

Just a message to share how to add this library on a Aws ElasticBeanstalk, by installing dependencies:

.ebextensions/02_install.config

commands:
   01_install_ghostscript:
       command: "sudo yum -y install ghostscript"
   02_install_graphicsmagick:
       command: "sudo amazon-linux-extras install GraphicsMagick1.3"
       # https://aws.amazon.com/amazon-linux-2/faqs/#Amazon_Linux_Extras

And your library set in your package.json to be installed with npm install

gm convert: abort due to signal 7 (SIGBUS) "Bus Error

module is working fine on windows, but when deployed to EC2 (ubuntu-bionic-18.04-amd64-server-20180912) it throws:
Error: Command failed: gm convert: abort due to signal 7 (SIGBUS) "Bus Error"...

screen shot 2019-02-11 at 4 25 12 pm

I have installed gm through:

sudo apt-get install graphicsmagick

and to confirm, I ran gm command manually and it worked:

gm convert pdfname.pdf imagename.png

so, is this something with plugin?

Lambda

Have way to example with binaries of ghoscript and imagemagick to working with serveless (lambda aws)?

multiple pages to images?

Does this convert each page to a separate image file? I can't tell from the docs.

If the pdf has 5 pages, will I get 5 image files out?

Thanks,
Donnie

rimraf dependency not present

Installation fails because the clean step is dependent on rimraf being in the path but it's not included as a dependency.

GM config to use imagemagick instead

Received Error: Command failed: gm convert: Coder did not return an image (this is a bug, please report it!) (/tmp/gmmSJZta) [No such file or directory]. when executing image conversion on ubuntu.

I solved this issue by updating const gm = require("gm").subClass({ imageMagick: true });

and then updating sudo vim /etc/ImageMagick-6/policy.xml with <policy domain="coder" rights="read|write" pattern="PDF" />

it would be great if imageMagick: true could be passed into the constructor instead of me having to fork the repo and update the code myself.

File stream option

Hi all,

Now, this lib returns an image location after conversion. Can we have the converted image file stream or buffer, please

as I am uploading the image to cloud an extra delete operation is needed now which is making one of API bit slower

Image width and height

When doing a bulkConvert, it would be nice to receive the width and height of the generated image in the callback. Awesome project! Thanks

Converting more than one slide at a time fails

On Mac OS 10.15.5 when I use the same PDF, I am able to convert each slide to a PNG, one slide at a time. However, if I specify more than one slide at a time or all slides, I get this error:

(node:88658) UnhandledPromiseRejectionWarning: Error: Command failed: GPL Ghostscript 9.52: Unrecoverable error, exit code 1
gm convert: "gs" "-q" "-dBATCH" "-dSAFER" "-dMaxBitmap=50000000" "-dNOPAUSE" "-sDEVICE=ppmraw" "-dTextAlphaBits=4" "-dGraphicsAlphaBits=4" "-r100x100" "-dFirstPage=18446744073709551615" "-dLastPage=18446744073709551615" "-sOutputFile=/var/folders/rw/mlnbjynj2qsc7bfjvx_wdxth0000gn/T/gmm0uuxL" "--" "/var/folders/rw/mlnbjynj2qsc7bfjvx_wdxth0000gn/T/gm8LT82h" "-c" "quit".
gm convert: Postscript delegate failed (/var/folders/rw/mlnbjynj2qsc7bfjvx_wdxth0000gn/T/gmpqgZXA).

    at ChildProcess.onExit (/Users/fstrecker/dev-ng/gw-server/node_modules/gm/lib/command.js:301:17)
    at ChildProcess.emit (events.js:198:13)
    at maybeClose (internal/child_process.js:982:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
(node:88658) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:88658) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

It seems that this also has an uncaught error that should be caught and dealt with to avoid the server being killed.

Debian 10 has the exact same issue. Just confirmed it.

An in-range update of babel7 is breaking the build 🚨


🚨 Reminder! Less than one month left to migrate your repositories over to Snyk before Greenkeeper says goodbye on June 3rd! 💜 🚚💨 💚

Find out how to migrate to Snyk at greenkeeper.io


There have been updates to the babel7 monorepo:

    • The devDependency @babel/cli was updated from 7.10.0 to 7.10.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the babel7 group definition.

babel7 is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v7.10.2

v7.10.2 (2020-05-30)

Thanks @fivetanley and @hamlim for their first PRs!

🚀 New Feature

🐛 Bug Fix

  • babel-helper-compilation-targets
    • #11648 fix: don't mutate InputTarget's passed to @babel/helper-compilation-targets (@fivetanley)
  • babel-helper-create-class-features-plugin, babel-preset-env
  • babel-generator
  • babel-generator, babel-types
  • babel-plugin-syntax-module-attributes, babel-standalone
    • #11631 Fix moduleAttributesVersion errors with stage-0 preset in babel standalone (@hamlim)

💅 Polish

  • babel-core
    • #11643 fix: add new plugin names to missing plugin helpers (@JLHwung)

🏠 Internal

  • babel-parser
    • #11653 refactor: split locationParser into ParserErrors and error message (@JLHwung)

Committers: 6

Commits

The new version differs by 11 commits.

  • b0350e5 v7.10.2
  • b5c4a46 refactor: split locationParser into ParserErrors and error message (#11653)
  • 15d6da0 fix: don't mutate InputTarget's passed to @babel/helper-compilation-targets (#11648)
  • e6d873e Class features loose should have precedence over preset-env (#11634)
  • 5b24d79 fix: add bigIntSuffix to minified output (#11645)
  • 69198be feature: babel-eslint-parser passes through config options (#11639)
  • 6b7a6dc fix: add new plugin names to missing plugin helpers (#11643)
  • d7d36a6 Add support for printing ImportAttribute (#11641)
  • 8e41f26 Fix moduleAttributesVersion errors with stage-0 preset in babel standalone (#11631)
  • ddfdf00 Update CHANGELOG.md [skip ci]
  • 1b670c2 Add v7.10.1 to CHANGELOG.md [skip ci]

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Expose gm option to support gm.exe in PowerShell

I work in Linux, Mac, and (ahem) Windows (haha), and happen to be on Windows now. In PowerShell pdf2image throws an error because the gm maps to something else. In PowerShell gm.exe is the command.

For now I have hacked the gm module like this for Windows.

image

GraphicsMagick offers an appPath argument (see screenshot).

import GM from 'gm'
const gm = GM.subClass({appPath: 'C:\\Program Files\\GraphicsMagick-1.3.26-Q8\\'})

via aheckmann/gm#681

It may be something worth supporting in your config.

Unfortunately it won't work in PowerShell without a hack as is. I'm not 100% sure what I'll do as I'm just testing the module. Got it to work now with this hack. Let's see how it goes

Getting low Image quality after conversion

Hi , I'm setting the pdf2pic options as follows

const pdf2pic = new PDF2Pic({
  density: 600,  // output pixels per inch
  quality:100,         
  savename: "untitled",   // output file name
  savedir: "/tmp",    // output file location
                });

an I tried setting size to higher resolution but every time both the image quality and resolution was not good

Conversion fails when image size is large

When a single PDF slide is too big, the conversion fails with this error in the logs:

2|main           | { Error: Command failed: GPL Ghostscript 9.26: Unrecoverable error, exit code 1
2|main           | gm identify: "gs" "-q" "-dBATCH" "-dSAFER" "-dMaxBitmap=50000000" "-dNOPAUSE" "-sDEVICE=pnmraw" "-dTextAlphaBits=4" "-dGraphicsAlphaBits=4" "-r72x72" "-sOutputFile=/tmp/gmcnskDT" "--" "/tmp/gmOBTdFt" "-c" "quit".
2|main           | gm identify: Unexpected end-of-file (/tmp/gmcnskDT).
2|main           | gm identify: Request did not return an image.
2|main           |     at ChildProcess.onExit (/opt/gw-server/node_modules/gm/lib/command.js:301:17)
2|main           |     at ChildProcess.emit (events.js:198:13)
2|main           |     at maybeClose (internal/child_process.js:982:16)
2|main           |     at Socket.stream.socket.on (internal/child_process.js:389:11)
2|main           |     at Socket.emit (events.js:198:13)
2|main           |     at Pipe._handle.close (net.js:607:12) code: 1, signal: null }

How can the minimum slide config be changed so that any size image / page can be converted? Presumably: -dMaxBitmap=50000000

run sample code failed

G:\Projects\node\convert-images>node index.js
(node:7136) UnhandledPromiseRejectionWarning: Error: Could not execute GraphicsMagick/ImageMagick: gm "identify" "-ping" "-format" "%p" "G:\Projects\node\convert-images\files\all-algo.pdf" this most likely means the gm/convert binaries can't be found
at ChildProcess. (G:\Projects\node\convert-images\node_modules\gm\lib\command.js:232:12)
at ChildProcess.emit (events.js:223:5)
at ChildProcess.cp.emit (G:\Projects\node\convert-images\node_modules\cross-spawn\lib\enoent.js:36:37)
at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)
(node:7136) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7136) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

memory leak

Is there a best practice when trying to convert a pdf file with a lot of pages (~500 pages)? "convertBulk" is creating a separate promise for each of the pages which is attempts to instantiate 500 gm instances. This quickly drains the memory and shoots the CPU use up. I've tried to submit a job in 10 page chucks but when I look at the activity monitor, the gm instances are still accumulating.

Error Using with Firebase Cloud Functions

I get an error that begins with Error: Could not execute GraphicsMagick/ImageMagick: gm "identify" "-ping" "-format" "%p" when attemping to run pdf2pic on a firebase cloud function.

I installed graphicsmagick using npm install gm and also installed imagemagick and then installed pdf2pic.

Versions:
"imagemagick": "^0.1.3",
"gm": "^1.23.1",
"pdf2pic": "^1.2.6",

Code:

I import the package
const PDF2Pic = require('pdf2pic').default;

and I'm doing a bulk conversion

let converter = new PDF2Pic({
            density: 150,           // output pixels per inch
            savename: savename,   // output file name
            savedir: outputDirectory,    // output file location
            format: 'jpg',          // output file format
            size: 3000,               // output size in pixels
        })
 var reply = converter.convertBulk(pdfPath, [13,14,15])
            .then( () => {
                console.log('image converted successfully');
        });

An in-range update of rollup is breaking the build 🚨

The devDependency rollup was updated from 1.26.4 to 1.26.5.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

rollup is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v1.26.5

2019-11-11

Bug Fixes

  • Fix a regression where it was no longer to pass a certain option format to generate (#3223)

Pull Requests

Commits

The new version differs by 3 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Empty string output

const options = {
    density: 300, // ppi
    format: "png",
    width,
    height
  }
  return pdf2pic.fromBuffer(buffer, options).bulk(1, true)
    .then(resizedImageBase64 => {

Hi I use your library regularly, thank you for making it.

I recently had an issue where the resizedImageBase64 above was an empty string. I was actually unable to replicate the issue on either my windows machine or within WSL.... I have it running in docker with the imagemagick and ghostscript packages installed and this is where the error is occurring.

However some research showed that ghostscript might silently fail if a font is not included in the PDF and the PDF i had the issue did not have the font included that the text used. I was hoping it might be possible to pass options through to ghostscript through this library in order to test this hypothesis. Is this possible?

Thanks

Could not execute GraphicsMagick/ImageMagick

Could not execute GraphicsMagick/ImageMagick: gm "identify" "-ping" "-format" "%p" "filename.pdf" this most likely means the gm/convert binaries can't be found
at ChildProcess. (/Users/saurabh/Desktop/IMap/node_modules/gm/lib/command.js:232:12)
at emitOne (events.js:116:13)
at ChildProcess.emit (events.js:211:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:196:12)
at onErrorNT (internal/child_process.js:362:16)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
at Function.Module.runMain (module.js:696:11)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3

Can't find ./dist/index.js when ./dist/index.min.js exists

Just built a project that was using pdf2pic, and came across an odd build error.

Error: Cannot find module './dist/index.js'
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/my-utility/node_modules/pdf2pic/index.js:3:18)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)

When I look in pdf2pic in node_modules, I see node_modules/pdf2pic/dist/index.min.js, not index.js. Is this intentional and I'm missing some config or is this a bug? It's like the published pdf2pic distribution is broken and it's not looking for the minified version.

Option to convert a Buffer or Base64

It would be nice to create an option to pass Buffer or base64 string a source instead of file_path. It can be useful when users create a PDF file and this file is never save on disc.

As far as I know, actually the library to convert PDF to image with Buffer or base64 input doesn't exist so it will be a huge advantage.

Setup prerequisite

I'm dumb - I'm using firebase nodejs and I can't understand how to install graphicsmagick and ghostscript there. Any help please?

I'd expect those modules to be available as npm packages but that doesn't seem to be the case. What is the expected way to set it up?

TypeError: a.split is not a function.

Hello everyone,
sorry my english is not very well.

I have a problem when I try to convert a file, I already installed Ghostscript and GraphicsMagick, can someone help me?

(node:8980) UnhandledPromiseRejectionWarning: TypeError: a.split is not a function at t.value (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\pdf2pic\dist\index.min.js:1:1343) at C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\pdf2pic\dist\index.min.js:1:1586 at Promise._execute (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\bluebird\js\release\debuggability.js:313:9) at Promise._resolveFromExecutor (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\bluebird\js\release\promise.js:488:18) at new Promise (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\bluebird\js\release\promise.js:79:10) at t.value (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\pdf2pic\dist\index.min.js:1:1558) at t.<anonymous> (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\pdf2pic\dist\index.min.js:1:5951) at tryCatch (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\regenerator-runtime\runtime.js:45:40) at Generator.invoke [as _invoke] (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\regenerator-runtime\runtime.js:271:22) at Generator.prototype.(anonymous function) [as next] (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\regenerator-runtime\runtime.js:97:21) at asyncGeneratorStep (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24) at _next (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9) at C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\@babel\runtime\helpers\asyncToGenerator.js:32:7 at new Promise (<anonymous>) at t.<anonymous> (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\@babel\runtime\helpers\asyncToGenerator.js:21:12) at t._createClass.value (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\pdf2pic\dist\index.min.js:1:6078) (node:8980) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:8980) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. (node:8980) UnhandledPromiseRejectionWarning: Error: Could not execute GraphicsMagick/ImageMagick: gm "identify" "-ping" "-format" "%p" "sample.pdf" this most likely means the gm/convert binaries can't be found at ChildProcess.<anonymous> (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\gm\lib\command.js:232:12) at ChildProcess.emit (events.js:189:13) at ChildProcess.cp.emit (C:\Users\fagner.batista\Documents\apiPdfLinux\node_modules\cross-spawn\lib\enoent.js:36:37) at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12) (node:8980) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Keep transparency

Hi,

I really this project, but I can´t get transparency to work.
Are this supported or am I doing something wrong?

my code:
const PDF2Pic = require('pdf2pic')
const pdf2pic = new PDF2Pic({
density: 300,
savename: req.file.filename + '.png',
savedir: uploadPath,
format: 'png',
size: '600x600'
})
pdf2pic.convertToBase64( ....

Take care.

5e396253becd8d3ecc1cec12.pdf
(the pdf contain a write, arrow)

Auto image proportion

Hi, is there a way to let the package handle the proportion without giving to it specific width and height?
I really appreciate any kind of help.

Pdf2pic typings and readme exemple

Hello,
I use Pdf2pic and just upgraded the package but there is one thing I don't understand :

So while I use to do :

  pdf2pic.convertToBase64(filename).then( img => ...

Now if I understand it has changed to :

fromPath(filePath, options).convert(1, true).then( img => ...

But I get the following typescript error :

Property 'convert' does not exist on type 'Convert'

So according to the typing file I should do :

fromPath(filePath, options)(1, true).then( img => ...

Can you confirm this ?

Thanks for the work by the way.

Using in Google Firebase Function

I'm getting permission errors when using it in a Firebase Function:

Error: Command failed: identify-im6.q16: not authorized `/tmp/magick-11MhuZ7RCzH5fc' @ error/constitute.c/ReadImage/412.

Has anybody managed to deploy it to a Firebase function and use it? How I'm using it:

const PAGE_NUMBER = -1; // -1 is to convert all pages
const storeAsImage = pdf2pic.fromBuffer(fileBuffer, options);
storeAsImage.setGMClass(true);
const convertedFileData: WriteImageResponse[] = await storeAsImage.bulk(PAGE_NUMBER);

TypeError: Cannot read property 'toString' of undefined

I tried using the pdf2pic library in React app. When conversion code is ran individually, Its working fine. But when the same code is imported in other component ,It is showing TypeError: Cannot read property 'toString' of undefined error. Please help me out.

require.js:5 Uncaught Error: Module name "pdf2pic" has not been loaded yet for context: _.

HI I am trying to use this mdoule . I am trying to run the module in a simple html file .
I am getting this Error:
require.js:5 Uncaught Error: Module name "pdf2pic" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at makeError (require.js:5)
at Object.o [as require] (require.js:5)
at requirejs (require.js:5)
at functionconverter (index.html:7)
at HTMLInputElement.onclick (index.html:20)
Please help !

code.txt

Issues with types (convert.d.ts)

Getting an error when using within a typescript app.

node_modules/pdf2pic/dist/index.d.ts:2:25 - error TS2307: Cannot find module '@module/types/convert' or its corresponding type declarations.

Screen Shot 2020-11-24 at 8 37 39 AM

Changing the import statement like so seems to fix the issue for me, but I'm not sure if maybe I'm missing something or I have a version mismatch?

import { WriteImageResponse } from "../types/writeImageResponse"; import { ToBase64Response } from "../types/toBase64Response";

Uncaught TypeError: Cannot read property 'native' of undefined

Hi,
in the object of the message the error that I receive generated by line 126 of fs-extra library.

My node version is v12.18.4
My npm version is 6.14.6

I simply installed the library with

npm i pdf2pic 

and I imported in my js file with

import {fromBase64} from 'pdf2pic'

Any solutions?
Thanks in advance.

An in-range update of rollup is breaking the build 🚨

The devDependency rollup was updated from 1.27.6 to 1.27.7.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

rollup is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v1.27.7

2019-12-01

Bug Fixes

  • Fix a scenario where a reassignments to computed properties were not tracked (#3267)

Pull Requests

Commits

The new version differs by 4 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

PNG not rendering on Mac

Hello. I have been using your pdf2pic library on a mac. I very much like the package. It is working as expected on one mac. However, on another, the same code produces some weirdness. Instead of rendering a PNG (as it does on the first mac), it renders a PDF. So it appears to be taking each page of the pdf and making a single-paged pdf document for it.

Was wondering if you have seen this and if there is perhaps a configuration issue that I am overlooking? I have gm and gs both installed on the macs.

pdf page count

I can specify the page number to be converted or the number -1 to convert all pages. Is there any way to know the page count to setup a loop? Possibly to await each page conversion or convert in batches until there are no other pages.

If not then this is a feature request. If yes could you tell me the trick?

By the way this plugin is awesome. Thank you.

Module Error

Hi,
I have a problem when i running your module and I don't understand why.
capture d ecran 2018-01-26 a 09 02 41

I'm on Mac OS HighSierra and NodeJS 9.2.0
Can you help me ?

Transpiler issue? Can only use "1.2.6"

If I specify "^1.2.6" or "^1.3.1" I get this:

Error: Cannot find module '@babel/polyfill'
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/ocr-utility/node_modules/pdf2pic/dist/index.min.js:1:160)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)

An in-range update of babel7 is breaking the build 🚨

There have been updates to the babel7 monorepo:

    • The devDependency @babel/cli was updated from 7.8.0 to 7.8.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the babel7 group definition.

babel7 is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Blob as input?

Will this work with a PDF in blob/buffer format as input?

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.