Realization method of PDF based on PHANTOMJS _javascript skills

Source: Internet
Author: User

This article illustrates the implementation method of PDF based on PHANTOMJS. Share to everyone for your reference, specific as follows:

Recently, in the Node.js project development, met the need to generate PDF, of course, PDF is not a new requirement, I can choose to take advantage of open source Pdfkit or other node PDF modules, or through the edge.js call. net/ PDF Library under Python to do the build PDF. But it seems to me that it takes us too much time to do these things anyway (the contents of the PDF report are complex), it is better to put all the drawing logic into the familiar html+css, fast, so that the changes in the PDF format and the logic of the graphics calculation to push the Ejs, Jade, such as the template engine, for future modifications to maintain the extension is a good choice. So choosing Phantomjs to load pages to generate PDFs is not a good choice for me, and for html+css I need to be compatible with only a WebKit browser, with no aversion to browser compatibility concerns. So just do it, I spent half an hour on the project to configure the Phantomjs Automation script (in each environment to be able to automatically gou), as well as the implementation of a simple page PDF conversion.

Rasterize.js (from 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 [Paperwidt
    H*paperheight|paperformat] [zoom] ');
    Console.log (' paper (PDF output) Examples: "5in*7.5in", "10cm*20cm", "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: ' 1
    CM '};
    } if (System.args.length > 4) {page.zoomfactor = system.args[4]; } page.open (address, function (status) {if (Status!== ' success ') {Console.log (' Unable to load ' aDdress! ');
      Phantom.exit ();
          else {window.settimeout (function () {page.render (output);
        Phantom.exit ();
      });
  }
    });

 }

On the node caller side, use the exec invoke command line input to get the file and return 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 '). exec;
  var utils = require ('./utils '). Utils;
  var nodeutil = require (' util ');
  var outPut = function (ID, req, res) {
    var path = Nodeutil.format ("Tmp/%s.pdf", Utils.guid.newId ());
    var port = req.app.settings.port;
    var pdfurl = Nodeutil.format ("%s://%s%s/pdf/%s", Req.protocol, Req.host, (port = | | port = 443?) ': ': ' + port ', id);
    EXEC (Nodeutil.format ("Phantomjs tool/rasterize.js%s A4", Pdfurl, Path), function (Error, stdout, stderr) {
      if (err or | | stderr) {
        res.send, error | | stderr);
        return;
      }
      Res.set (' Content-type ', ' application/pdf ');
      Res.download (path)
  ;}; Exports.pdfutils = {
    output:output
  };

The code of the response can also be well converted to java/c# ... Command line is used to get PDFs and push them into the response stream. It's all so easy to fix.

Node also has a Node-phantom module, but it's a bit weird to use it to produce PDF styles, so it's a last resort to exec.

And then there's the Phantomjs. PDF does not bring the background color of the CSS and background images, so for this piece of exclusive use of a solid-color image of the IMG tag, and position:relative or absolute to locate the text. This is fine because the user on this page will not read it.

More readers interested in JavaScript-related content can view the site topics: "JavaScript switching effects and tips summary", "JavaScript Search Algorithm Skills Summary", "JavaScript animation effects and tips summary", " JavaScript error and debugging skills Summary, JavaScript data structure and algorithm skills summary, JavaScript traversal algorithm and skills summary and JavaScript mathematical calculation usage Summary

I hope this article will help you with JavaScript programming.

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.