Phantomjs 生成多頁PDF示例
最近使用 Phantomjs 生 成PDF,其中遇到一些問題,導致PDF生成失敗,如出現空白文件或一頁數據量太大,都是由于沒有設置好格式導致。特別是分頁問題,感覺資料很少,除了在 StackOverflow 上看到些許資料外,中文社區基本看不到,附上修改后的 rasterize.js 來做講解:
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", "10cm*20cm", "A4", "Letter"‘); phantom.exit(1);} else { address = system.args[1]; output = system.args[2]; /*size of browser*/ 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: ‘A4‘, orientation: ‘portrait‘, margin: ‘1cm‘ }; } */ /* ie and Chrome view diffrent format of pdf */ page.settings.userAgent = ‘Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36‘; page.paperSize = { format: ‘A4‘, orientation: ‘portrait‘, margin: ‘0.8cm‘ }; page.zoomFactor = 1; page.settings.loadImages = true; //some question about the page language page.open(address, function (status) { if (status !== ‘success‘) { console.log(‘Unable to load the address!‘); } else { //page.render(output); //phantom.exit(); window.setTimeout(function () { page.render(output); phantom.exit(); }, 200); //setting the time is enough to loading the page. document.ready } });}PDF 格式設置
關于其中 page 的設置屬性,這里可以了解,更深入可以了解 WebPage Module。
我們需要的設置,基本上就是頁面格式、縮放、加載圖片等,但有些例外,下面一一講解。
1 page.paperSize = { format: ‘A4‘, orientation: ‘portrait‘, margin: ‘0.8cm‘ }; 注釋掉了官方例子的設置代碼,因為傳入的參數只有3個,到 .pdf 為止,如果寫成通用模式,當然可以作為外部參數傳入。
format :A4 紙,可以設置 "5in*7.5in", "10cm*20cm", "Letter" 等
orientation :紙方向是豎著的,或者 landscape
margin :與紙四邊間距,可自定義,也可詳細設置 margin : { left: ‘0.8cm‘, top : ‘0.8cm‘, right : ‘0.8cm‘, bottom : ‘0.8cm‘ }
1 page.zoomFactor = 1;2 page.settings.loadImages = true;zoomFactor :頁面縮放比例
loadImages :頁面加載圖片
1 page.settings.userAgent = ‘Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36‘;這個設置比較不常見,一般的示例中都沒有提及,因為發現用 chrome 和 IE 打開生成的 pdf 時格式有點不一樣(表現在分頁方面),由于偏向 Chrome 瀏覽格式,故設置此值,解決這個不一致問題。
page.open 里面的 setTimeout 方法作用:等待頁面執行完 js ,再生成 pdf。當然對于 js 要執行多久(要等多久),這個就不知道怎么預算了。其實我有試過 Ajax 方式加載內容,但因此問題而作罷了。
更多的信息,關于頁眉和頁腳及頁碼標注問題,可以參考這里。
PDF 分頁
分頁來說,更好控制,不需要代碼(js)設置,頁面使用樣式即可:
style = “page-break-after: always;”控制每頁內容的大小,使用 <div style="page-break-after: always;">content</div> 就行。
更多選擇 style=“page-break-before: always;” , style="page-break-inside: avoid;" 這個可以避免內容散到兩頁中
新聞熱點
疑難解答