Path: blob/master/6-Selenium/phantomjs/examples/printheaderfooter.js
164 views
var page = require('webpage').create(),1system = require('system');23function someCallback(pageNum, numPages) {4return "<h1> someCallback: " + pageNum + " / " + numPages + "</h1>";5}67if (system.args.length < 3) {8console.log('Usage: printheaderfooter.js URL filename');9phantom.exit(1);10} else {11var address = system.args[1];12var output = system.args[2];13page.viewportSize = { width: 600, height: 600 };14page.paperSize = {15format: 'A4',16margin: "1cm",17/* default header/footer for pages that don't have custom overwrites (see below) */18header: {19height: "1cm",20contents: phantom.callback(function(pageNum, numPages) {21if (pageNum == 1) {22return "";23}24return "<h1>Header <span style='float:right'>" + pageNum + " / " + numPages + "</span></h1>";25})26},27footer: {28height: "1cm",29contents: phantom.callback(function(pageNum, numPages) {30if (pageNum == numPages) {31return "";32}33return "<h1>Footer <span style='float:right'>" + pageNum + " / " + numPages + "</span></h1>";34})35}36};37page.open(address, function (status) {38if (status !== 'success') {39console.log('Unable to load the address!');40} else {41/* check whether the loaded page overwrites the header/footer setting,42i.e. whether a PhantomJSPriting object exists. Use that then instead43of our defaults above.4445example:46<html>47<head>48<script type="text/javascript">49var PhantomJSPrinting = {50header: {51height: "1cm",52contents: function(pageNum, numPages) { return pageNum + "/" + numPages; }53},54footer: {55height: "1cm",56contents: function(pageNum, numPages) { return pageNum + "/" + numPages; }57}58};59</script>60</head>61<body><h1>asdfadsf</h1><p>asdfadsfycvx</p></body>62</html>63*/64if (page.evaluate(function(){return typeof PhantomJSPrinting == "object";})) {65paperSize = page.paperSize;66paperSize.header.height = page.evaluate(function() {67return PhantomJSPrinting.header.height;68});69paperSize.header.contents = phantom.callback(function(pageNum, numPages) {70return page.evaluate(function(pageNum, numPages){return PhantomJSPrinting.header.contents(pageNum, numPages);}, pageNum, numPages);71});72paperSize.footer.height = page.evaluate(function() {73return PhantomJSPrinting.footer.height;74});75paperSize.footer.contents = phantom.callback(function(pageNum, numPages) {76return page.evaluate(function(pageNum, numPages){return PhantomJSPrinting.footer.contents(pageNum, numPages);}, pageNum, numPages);77});78page.paperSize = paperSize;79console.log(page.paperSize.header.height);80console.log(page.paperSize.footer.height);81}82window.setTimeout(function () {83page.render(output);84phantom.exit();85}, 200);86}87});88}899091