save_script_tpl.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. var page = require('webpage').create();
  2. var format = '#{format}';
  3. var data = '#{data}';
  4. var scale = parseFloat('#{scale}', 10);
  5. var width = parseInt('#{width}', 10);
  6. var height = parseInt('#{height}', 10);
  7. try {
  8. var pdfOptions = JSON.parse('#{pdf}' || null);
  9. } catch (e) {
  10. console.error("Parsing PDF options failed.");
  11. }
  12. try {
  13. var jpegOptions = JSON.parse('#{jpeg}' || null);
  14. } catch (e) {
  15. console.error("Parsing JPEG options failed.");
  16. }
  17. if (format === 'pdf') {
  18. page.paperSize = pdfOptions || { format: 'Letter', orientation: 'portrait', border: '1cm' };
  19. }
  20. page.content = '<img id="chart" src="' + data + '" style="-webkit-transform-origin: left top">';
  21. // Let the content to render, then adjust viewport, clipRect and image size.
  22. window.setTimeout(adjustSize, 1);
  23. function adjustSize() {
  24. var naturalSize = page.evaluate(function () {
  25. // By default the body has some margin, but we don't want that to be a part of the rendered image.
  26. var style = document.createElement('style'),
  27. text = document.createTextNode('body { margin: 0 }');
  28. style.setAttribute('type', 'text/css');
  29. style.appendChild(text);
  30. document.head.insertBefore(style, document.head.firstChild);
  31. var img = document.getElementById('chart');
  32. return {
  33. width: img.naturalWidth,
  34. height: img.naturalHeight
  35. };
  36. });
  37. if (width && height) {
  38. if (width !== naturalSize.width || height !== naturalSize.height) {
  39. page.viewportSize = { width: width, height: height };
  40. page.clipRect = { left: 0, top: 0, width: width, height: height };
  41. }
  42. }
  43. width = Math.round((width || naturalSize.width) * scale);
  44. height = Math.round((height || naturalSize.height) * scale);
  45. page.evaluate(function (width, height) {
  46. var img = document.getElementById('chart');
  47. img.style.width = width;
  48. img.style.height = height;
  49. }, width, height);
  50. // Let the image to scale before rendering.
  51. window.setTimeout(render, 1);
  52. }
  53. function render() {
  54. page.render('#{filename}', { format: format, quality: jpegOptions && jpegOptions.quality || 80 });
  55. phantom.exit();
  56. }