rasterize.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. var page = require('webpage').create(),
  3. system = require('system'),
  4. address, output, size;
  5. if (system.args.length < 3 || system.args.length > 5) {
  6. console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');
  7. console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');
  8. console.log(' image (png/jpg output) examples: "1920px" entire page, window width 1920px');
  9. console.log(' "800px*600px" window, clipped to 800x600');
  10. phantom.exit(1);
  11. } else {
  12. address = system.args[1];
  13. output = system.args[2];
  14. page.viewportSize = { width: 600, height: 600 };
  15. if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {
  16. size = system.args[3].split('*');
  17. page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' }
  18. : { format: system.args[3], orientation: 'portrait', margin: '1cm' };
  19. } else if (system.args.length > 3 && system.args[3].substr(-2) === "px") {
  20. size = system.args[3].split('*');
  21. if (size.length === 2) {
  22. pageWidth = parseInt(size[0], 10);
  23. pageHeight = parseInt(size[1], 10);
  24. page.viewportSize = { width: pageWidth, height: pageHeight };
  25. page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight };
  26. } else {
  27. console.log("size:", system.args[3]);
  28. pageWidth = parseInt(system.args[3], 10);
  29. pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any
  30. console.log ("pageHeight:",pageHeight);
  31. page.viewportSize = { width: pageWidth, height: pageHeight };
  32. }
  33. }
  34. if (system.args.length > 4) {
  35. page.zoomFactor = system.args[4];
  36. }
  37. page.open(address, function (status) {
  38. if (status !== 'success') {
  39. console.log('Unable to load the address!');
  40. phantom.exit(1);
  41. } else {
  42. window.setTimeout(function () {
  43. page.render(output);
  44. phantom.exit();
  45. }, 200);
  46. }
  47. });
  48. }