New Choice for generating PDF-Phantomjs

Source: Internet
Author: User

Recently in node. in js project development, PDF generation is not a new requirement. I can choose to use open source development kit or other node PDF modules, or use edge. js call. net/python pdf library to generate pdf. However, in my opinion, it takes too much time for these things (the content reports of pdf reports are complex ), it is better to push all the drawing implementation logic to the concise and fast html + css that everyone is familiar, in this way, changes in the pdf format and graphic computing logic are pushed to templates engines such as ejs and jade, which is a good choice for future modification and maintenance extension. Therefore, choosing phantomjs to load the page to generate PDF is not a good choice for me. At the same time, for html + css, I only need a webkit browser that is compatible with each other, and there is no dislike of browser compatibility concerns. So let's do it. I spent half an hour in the project to configure the automatic scripts of phantomjs in various environments to automatically hook up and implement PDF conversion of a simple page.

Rasterize. js is from the official pdf demo ):

Var page = require ('webpage'). create (),

System = require ('system '),

Address, output, size;


If (system. args. length <3 | system. args. length> 5 ){

Console. log ('usage: rasterize. js URL filename [paperwidth * paperheight | paperformat] [zoom] ');

Console. log ('paper (pdf output) examples: "5in * 7.5in", "10 cm * 20 cm", "A4", "Letter "');

Phantom. exit (1 );

} Else {

Address = system. args [1];

Output = system. args [2];

Page. viewportSize = {width: 600, height: 600 };

If (system. args. length> 3 & system. args [2]. substr (-4) = ". pdf "){

Size = system. args [3]. split ('*');

Page. paperSize = size. length = 2? {Width: size [0], height: size [1], margin: '0px '}

: {Format: system. args [3], orientation: 'portrait', margin: '000000 '};

}

If (system. args. length> 4 ){

Page. zoomFactor = system. args [4];

}

Page. open (address, function (status ){

If (status! = 'Success '){

Console. log ('unable to load the address! ');

Phantom. exit ();

} Else {

Window. setTimeout (function (){

Page. render (output );

Phantom. exit ();

});

}

});

}

On the node caller, use exec to call the command line to input the file and return it to the node response stream:

Guid utils:

'Use strict ';


Var guid = function (){

Var uid = 0;

This. newId = function (){

Uid = uid % 1000;

Var now = new Date ();

Var utc = new Date (now. getTime () + now. getTimezoneOffset () * 60000 );

Return utc. getTime () + uid ++;

}

}


Exports. utils = {

Guid: new guid ()

};

Pdfutil:

'Use strict ';


Var exec = require('child_process'cmd.exe c;

Var utils = require ('./utils'). utils;

Var nodeUtil = require ('til ');


Var outPut = function (id, req, res ){

Var path = nodeUtil. format ("tmp/%s.pdf", utils. guid. newId ());

Var port = req. app. settings. port;

Var required url = nodeUtil. format ("% s: // % s/pdf/% s", req. protocol, req. host, (port = 80 | port = 443? '': '+ Port), id );


Exec (nodeUtil. format ("phantomjs tool/rasterize. js % s A4", signed URL, path), function (error, stdout, stderr ){

If (error | stderr ){

Res. send (500, error | stderr );

Return;

}

Res. set ('content-type', 'application/pdf ');

Res. download (path );

});


};


Exports.pdf Utils = {

OutPut: outPut

};

The response code can also be converted to the java/c #... command line call to get the pdf and push it to the response stream. Everything is so easy.

Node also has the node-phantom module, but the pdf style generated by it is a bit strange, so it still insisted on using the exec method.

In addition, the background color of css and the Beijing image are not included in the PDF generated by phantomjs. Therefore, the img label of the solid color image is used and the position: relative or absolute is used to locate the text. this is fine because users on this page will not see it,

The article also ends here. I hope to talk more and continue to pay attention to it. Thank you.


This article from the "wolf" blog, please be sure to keep this source http://whitewolfblog.blog.51cto.com/3973901/1339027

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.