Giter Site home page Giter Site logo

nodepdf's Introduction

NodePDF

Down and dirty PDF rendering in Node.js

Build Status

Installation

npm install nodepdf

Dependencies

  1. PhantomJS

Contsructor API

You can use NodePDF two ways, one is using a contstructor that returns an instance of EventEmitter.

var NodePDF = require('nodepdf');

// last argument is optional, sets the width and height for the viewport to render the pdf from. (see additional options)
var pdf = new NodePDF('http://www.google.com', 'google.pdf', {
	'viewportSize': {
		'width': 1440,
		'height': 900
	}, 
	'args': '--debug=true'
});

pdf.on('error', function(msg){
	console.log(msg);
});

pdf.on('done', function(pathToFile){
	console.log(pathToFile);
});

// listen for stdout from phantomjs
pdf.on('stdout', function(stdout){
	 // handle
});

// listen for stderr from phantomjs
pdf.on('stderr', function(stderr){
	// handle
});

Or set the content directly instead of using a URL:

var pdf = new NodePDF(null, 'google.pdf', {
	'content': '<html><body><img src="https://www.google.com/images/srpr/logo11w.png" alt="google"/></body></html>',
	'viewportSize': {
		'width': 1440,
		'height': 900
	},
});

You can set the header and footer contents as well:

var NodePDF = require('nodepdf');
var pdf = new NodePDF('http://yahoo.com', 'yahoo.pdf', {
	'viewportSize': {
		'width': 3000,
		'height': 9000
	},
	'paperSize': {
		'pageFormat': 'A4',
		'margin': {
			'top': '2cm'
		},
		'header': {
			'height': '1cm',
			'contents': 'HEADER {currentPage} / {pages}' // If you have 2 pages the result looks like this: HEADER 1 / 2
		},
		'footer': {
			'height': '1cm',
			'contents': 'FOOTER {currentPage} / {pages}'
		}
	},
	'outputQuality': '80',
	'zoomFactor': 1.1
});

Callback API

The callback API follows node standard callback signatures using the render() method.

var NodePDF = require('nodepdf');

// options is optional, sets the width and height for the viewport to render the pdf from. (see additional options)
NodePDF.render('http://www.google.com', 'google.pdf', options, function(err, filePath){
	// handle error and filepath
});

// use default options
NodePDF.render('http://www.google.com', 'google.pdf', function(err, filePath){
	// handle error and filepath
});

As soon the content option is set, the URL is ignored even if you set one.

Options + Defaults

{
	'viewportSize': {
		'width': 2880,
		'height': 1440
	},
	'paperSize': {
		'format': 'A4',
		'orientation': 'portrait',
		'margin': {
			'top': '1cm',
			'right': '1cm',
			'bottom': '1cm',
			'left': '1cm'
		}
	},
	'outputQuality': '80', //set embedded image quality 0 - 100
	'zoomFactor': 1,
	'args': '',
	'captureDelay': 400

}

You can set all the properties from here: http://phantomjs.org/api/webpage/

Cookies

var NodePDF = require('nodepdf');
var pdf = new Pdf('http://yahoo.com', 'yahoo.pdf', {
	'cookies': [
		{
			'name':     'Valid-Cookie-Name 1',   /* required property */
			'value':    'Valid-Cookie-Value 1',  /* required property */
			'domain':   'localhost',           /* required property */
			'path':     '/foo',
			'httponly': true,
			'secure':   false,
			'expires':  (new Date()).getTime() + (1000 * 60 * 60)   /* <-- expires in 1 hour */
		},
		{
			'name':     'Valid-Cookie-Name 2',
			'value':    'Valid-Cookie-Value 2',
			'domain':   'localhost'
		}
	]
});

PhantomJS Cookie Object description: http://phantomjs.org/api/webpage/property/cookies.html

License

(The MIT License)

Copyright (c) 2013 TJ Krusinski <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

nodepdf's People

Contributors

bromanko avatar emadow avatar hideov avatar mbelshe avatar mk-pmb avatar n3o77 avatar philip-peterson avatar robbschiller avatar russmatney avatar smithatlanta avatar tjkrusinski 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nodepdf's Issues

TypeError: undefined is not an object (evaluating 'phantom.args.length')

PhantomJS is installed and on the path, I ran "npm install phantom" and "npm install nodepdf" and everything seems to have gone fine. Still, running your samples results in

TypeError: undefined is not an object (evaluating 'phantom.args.length')

Being printed to stdout.

Node v0.12.0
Windows 7 x64

Issue with the header and footer options

Hi,

I am having an issue with the header and footer option. When I place an attribute into a html tag like style='some css'. The header and footer does not show. I think there is an issue with the quotations within quotations. Like so:

'header': {
                    'height': '1cm',
                    'contents': "<span style='text-align:center'><small>" + titleheader + "</small></span>"
},
'footer': {
                    'height': '1cm',
                    'contents': '<span style="text-align:right"><small>{currentPage}</small></span>'
}

Thou, it does work without the attributes. Like so:

'header': {
                    'height': '1cm',
                    'contents': "<center><small>" + titleheader + "</small></center>" 
},
'footer': {
                    'height': '1cm',
                    'contents': '<span><center><small>{currentPage}</small></center></span>'
}

It will be great if I can align the footer page numbers to the right of the PDF.

Thanks!

Unable to set custom Font type

The PDF generation process is working properly, but I am unable to set custom font type to the generated PDF document.

Also, the zoomFactor is not working. I have hosted my website in AWS EC2 Linux Instance.

Processing file gets created in a Temp directory

Upon running the following code ...
NodePDF.render('http://www.google.com', 'google.pdf', function(err, filePath){
console.log(filePath);
});

"www.google.com" file gets created into HEQOS3~P directory in root (I think http:// is getting encoded into directory name). I have reinstalled phantomjs, nodejs and the plugin few times over last two days on Ubuntu but no dice.

render.js debugs looks good.

For some reason instead of creating the pdf, processing file is getting created. Increasing captureDelay has no effect.

phantomjs /usr/share/doc/phantomjs/examples/rasterize.js 'http://www.google.com' google.pdf
works perfectly.

can't work with angular

How can I make it work with angular?
now it only can save the base html without angular's view, how can I make it work after the page load the view?

render.js fails to start if `stdin.length` exceeds system's command length

Because Pdf arguments are eventually passed in to the phantomjs script as command line arguments, if their combined length is too long the command can exceed the system's maximum command length. When this happens render.js fails to execute, but this case is not checked so the call to Pdf hangs indefinitely. I ran in to this problem by setting opts.content to a large html string composed of embedded base64 images. You will find an example of the issue in the gist below. I have a fix that spawns off an instance of getconf and emits and error if the phantomjs command exceeds the system's limit but I think the ideal solution would be to stream Pdf arguments in to render.js through stdin after the script starts. That way there would not be a limit at all.

https://gist.github.com/chris--young/be26ebf352643df4773f

Wait for all async to be done

Hi,

Great tool.

I'm just curios if there is a way to handle page loaded event.
For instance by observing window.status variable that will be set in some point of time.

Or probably calling back phantom method window.callPhantom and render would then listen to page.onCallback, which sounds much more exciting to me :)

Either way, keep up the goo work, and thank you in advance

Unable to parse JSON string: node_modules/nodepdf/render.js:16

Hi,

I'm having issues generating a PDF that actually embeds proper HTML.

My code works for a options.content = '

This is the body

' but it starts breaking as soon as i'm embedding a slightly more complicated HTML.

i.e, only setting the content to: '

This is the body

' makes it break with the above mentioned error.

It also breaks if I use the following example displayed on the home page:

var PDF = new NodePDF(null, 'google.pdf', {
    'content': '<html><body><img src="https://www.google.com/images/srpr/logo11w.png" alt="google"/></body></html>',
    'viewportSize': {
      'width': 1440,
      'height': 900
    }
})

Do you know what the issue is?
Many thanks

PhantomJS debug messages are being passed to the error handler

Hi,

I'm running the sample app defined in the README for the project.

However I'm finding that all the PhantomJS debug messages are being passed through to the error handler. So my error handler is being called 40 times per PDF conversion.

Any idea what I might be doing wrong or what i can change?

Can not call method 'call'

Hi Krusinski..
Thanks for the great module...
Though I got the pdf file generated, I kept getting the below error msg, which make me worry how the module is stable, and releable for production environment,,

Can you pls look into this, thanks

"TypeError: Cannot call method 'call' of undefined TypeError: Cannot call method
'call' of undefined
    at D:\rectoPG\node_modules\nodepdf\index.js:62:23
    at D:\rectoPG\node_modules\nodepdf\child.js:18:10
    at ChildProcess.exithandler (child_process.js:710:5)
    at ChildProcess.EventEmitter.emit (events.js:107:17)
    at maybeClose (child_process.js:825:16)
    at Socket.<anonymous> (child_process.js:1042:11)
    at Socket.EventEmitter.emit (events.js:104:17)
    at Pipe.close (net.js:458:12)
--------------------------------------------------------------------
TypeError: Cannot call method 'call' of undefined TypeError: Cannot call method
'call' of undefined
    at readStream (D:\rectoPG\node_modules\nodepdf\index.js:76:23)
    at Socket.<anonymous> (D:\rectoPG\node_modules\nodepdf\index.js:81:3)
    at Socket.EventEmitter.emit (events.js:126:20)
    at readableAddChunk (_stream_readable.js:156:16)
    at Socket.Readable.push (_stream_readable.js:123:10)
    at Pipe.onread (net.js:511:20)
--------------------------------------------------------------------

Error when parsing json options in Windows

It seems that there is a problem when parsing options at Windows 8;

I'm having this problem at line 18 in render.js, the string with the options come without quotes, so JSON cant parse.

Thats what its trying to execute:

phantomjs  C:\\Publix\\Dev\\node_modules\\nodepdf/render.js http://yahoo.com yahoo.pdf "{'viewportSize':{'width':2880,'height':1440},'paperSize':{'format':'A4','orientation':'portrait','margin':{'top':'1cm','right':'1cm','bottom':'1cm','left':'1cm'}},'zoomFactor':1,'args':'','captureDelay':400}"

But then the argument goes to render.js there is no quotes:

{viewportSize:{width:2880,height:1440},paperSize:{format:A4,orientation:portrait,margin:{top:1cm,right:1cm,bottom:1cm,left:1cm}},zoomFactor:1,args:,captureDelay:400}

I made some tests, the correct json string should be escaped with "":

phantomjs  C:\\Publix\\Dev\\node_modules\\nodepdf/render.js http://yahoo.com yahoo.pdf "{\"viewportSize\":{\"width\":2880,\"height\":1440},\"paperSize\":{\"format\":\"A4\",\"orientation\":\"portrait\",\"margin\":{\"top\":\"1cm\",\"right\":\"1cm\",\"bottom\":\"1cm\",\"left\":\"1cm\"}},\"zoomFactor\":1,\"args\":\"\",\"captureDelay\":400}"

Error occurred when then html is "too big"

I have a 2.1MB html. When I try to render the PDF, like this:

NodePDF.render(null, 'report.pdf', {
  'content': reportData,
  'viewportSize': {
    'width': 1440,
    'height': 900
  },
},function(err, filePath){
    console.log('err:' + err);
});

I got this error:

internal/child_process.js:298
    throw errnoException(err, 'spawn');
    ^

Error: spawn E2BIG
    at exports._errnoException (util.js:870:11)
    at ChildProcess.spawn (internal/child_process.js:298:11)
    at exports.spawn (child_process.js:362:9)
    at Object.exports.execFile (child_process.js:151:15)
    at Object.exports.exec (child_process.js:111:18)
    at Object.exports.exec (/report-project/node_modules/nodepdf/child.js:27:16)
    at /report-project/node_modules/nodepdf/index.js:133:20
    at /report-project/node_modules/nodepdf/child.js:38:12
    at ChildProcess.exithandler (child_process.js:204:7)
    at emitTwo (events.js:87:13)
    at ChildProcess.emit (events.js:172:7)
    at maybeClose (internal/child_process.js:818:16)
    at Socket.<anonymous> (internal/child_process.js:319:11)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at Pipe._onclose (net.js:469:12)

Ignore ssl errors

I had the following error with an ssl webpage:
2015-10-21T16:31:01 [DEBUG] Network - SSL Error: "The host name did not match any of the valid hosts for this certificate"

2015-10-21T16:31:01 [DEBUG] Network - SSL Error: "No error"
2015-10-21T16:31:01 [DEBUG] Network - SSL Error: "No error"

2015-10-21T16:31:01 [DEBUG] Network - Resource request error: 6 ( "SSL handshake failed" ) URL: "https://localhost/"

Where can I put the phanthom js flags?. Thanks

Getting Error: spawn E2BIG

when i try for big data i am getting this error

internal/child_process.js:302
    throw errnoException(err, 'spawn');
    ^

Error: spawn E2BIG
    at exports._errnoException (util.js:953:11)
    at ChildProcess.spawn (internal/child_process.js:302:11)
    at exports.spawn (child_process.js:372:9)
    at Object.exports.execFile (child_process.js:139:15)
    at Object.exports.exec (child_process.js:99:18)

'redirection unexpected'

Hi,

I encountered this error while using this module in Ubuntu server (14.04 LTS)

pdfgenerator stderr /bin/sh: 1: 
pdfgenerator stderr Syntax error: redirection unexpected
pdfgenerator stderr 
error in pdfgenerator: PDF conversion failed with exit of 2

From my research, it's could be because of Ubuntu's default shell, which is Dash (/bin/sh) and it should be /bin/bash shell. *http://stackoverflow.com/questions/2462317/bash-syntax-error-redirection-unexpected

Additionally, the /etc/passwd file shows that the account that I used to run the code has /bin/bash as its default shell.

any idea on this matter?

Here is my code:

            var html = ejs.render(templateString, <object_to_render>);

            var filename = 'application-'+app._id + '.pdf';
            var filepath = config.generatedDir + '/' + filename;

            var pdf = new NodePDF(null, filepath, {
                'content': html,
                'args': '--debug=true',
                'paperSize': {
                    'pageFormat': 'A4',
                    'footer': {
                        'height': '0.7cm',
                        'contents': '<p style="text-align:center">{currentPage} / {pages}</p>'
                    }
                },
                'zoomFactor': 1.1
            });

            pdf.on('error', function(msg){
                console.log('error in pdfgenerator:', msg);
            });

            pdf.on('done', function(filePath){
                console.log(filePath);
                if (filePath) {
                    //save file information to database
                }
            });

            pdf.on('stdout', function(stdout){
                console.log('pdfgenerator stdout', stdout);
            });


            pdf.on('stderr', function(stderr){
                console.log('pdfgenerator stderr', stderr);
            });

appreciate any help.
thank you.

Calling phantomJS from NodePDF

Is it possible to call phantomJS functions from within the NodePDF class? I would like to have custom header depending on the page number:

var NodePDF = require('nodepdf');

var pdf = new NodePDF('http://www.yahoo.com', 'yahoo.pdf', {
    'viewportSize':{
        'width':3000,
        'height':9000
    },
    'paperSize': {
        'pageFormat': 'A4',
        'margin': {
            'top': '2cm'
        },
        'header': {
          'height': "1cm",
          'contents': phantom.callback(function(pageNum, numPages) {
            if(pageNum == 1) {
                return "";
            } else {
                return "<h1>Header <span style='float:right'>" + pageNum + " / " + numPages + "</span></h1>";
            }
          })
        },
        'footer': {
            'height': '1cm',
            'contents': 'FOOTER {currentPage} / {pages}'
        }
    },
    'zoomFactor': 1.1
});

Phantom 2.0 supported?

Hi,

I've used this module before and it worked like a charm.
Now on a new computer I've installed Phanthom.js 2.0.
The module now doesn't seem to work.
Using the example code i get this in my terminal.

Is this correct (because 2.0 is not supported) OR am I doing something wrong?

Thx in advance!

2015-09-07T16:15:30 [DEBUG]      2 arg: "{"viewportSize":{"width":1440,"height":900},"paperSize":{"format":"A4","orientation":"portrait","margin":{"top":"1cm","right":"1cm","bottom":"1cm","left":"1cm"}},"outputQuality":"80","zoomFactor":1,"args":"--debug=true","captureDelay":400}"
2015-09-07T16:15:30 [DEBUG] Phantom - execute: Starting normal mode

2015-09-07T16:15:30 [DEBUG] WebPage - setupFrame ""

2015-09-07T16:15:30 [DEBUG] FileSystem - _open: ":/modules/fs.js" QMap(("mode", QVariant(QString, "r") ) ) 

2015-09-07T16:15:30 [DEBUG] FileSystem - _open: ":/modules/system.js" QMap(("mode", QVariant(QString, "r") ) ) 

2015-09-07T16:15:30 [DEBUG] FileSystem - _open: ":/modules/webpage.js" QMap(("mode", QVariant(QString, "r") ) ) 

TypeError: undefined is not an object (evaluating 'phantom.args.length')

  /path-to-project/node_modules/nodepdf/render.js:11 in global code

Out.pdf doesn't show text but ■■■■■

Hi
I've used nodepdf on windown and ubuntu and it always worked fine.

I'm currently using centos 7 on linode server and the output file i get just shows ■■■ instead of text in out.pdf file

Path to file coming back wrong

Using version.0.0.5, File is being saved as

/applicationroot/filename.pdf

and reporting

/applicationroot/node_modules/nodepdf/filename.pdf

Feature Request: Add Cookie to page request.

I'd put a pull reuest in, but I can't get it to work.

https://github.com/ariya/phantomjs/wiki/API-Reference#appendix

I added the following to render.js.

var page = require('webpage').create();


page.addCookie({
    'domain':'localhost',
    'name': 'connect.sid',
    'value': 's:ePzRBZk5KjCRhHV-UrCSHrGv.uz0aLkqm/9DaO/uMlXt6j8D89/5GTW19caz/wE/DHjU'
});


if (phantom.args.length < 2) {
    console.log('11');
    console.log('incorrect args');
    phantom.exit();

I checked the request headers on the server, and the cookie simply isn't being added. I'm not sure if you have any suggestions.

Thanks for your time,
Jozz

Duplicate hyperlink

Hi,

NodePDF creates a duplicate hyperlink on the PDF if one exists on the htlml page, any solution to this issue?

[Error: Conversion failed with exit of 4294967295]

Hi,

When I use nodepdf in a seperate nodejs project, it is working fine, whereas if I use it in a Nodejs project with express framework, I am getting the below error:

[Error: Conversion failed with exit of 4294967295]

I couldn't trace the reason for the error. I am not sure if am doing something wrong!

Thanks!

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.