phantomjs html to PDF

來源:互聯網
上載者:User

標籤:ror   orm   方式   path   src   server   overflow   property   定義   

 

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Configuration;using System.IO;/// <summary>///PDFCommon 的摘要說明/// </summary>public class PDFCommon{public PDFCommon(){}    public static string CreatePDF(string url)    {        string fileNameWithOutExtention = Guid.NewGuid().ToString();        string path = System.Web.HttpContext.Current.Server.MapPath(@"~\bin\phantomjs\");        //string paths = System.Web.HttpContext.Current.Server.MapPath(@"~\chartPdfFile");        string savePath = Path.Combine(@"D:/", string.Format("{0}.pdf", Guid.NewGuid()));        string filePath = Path.Combine(path, "phantomjs.exe");        string jsPath = Path.Combine(path, "generate_pdf.js");        string argument = string.Format(" --ignore-ssl-errors=yes  {0} \"{1}\" {2}", jsPath, url, savePath);        using (System.Diagnostics.Process exep = new System.Diagnostics.Process())        {            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();            startInfo.FileName = filePath;            startInfo.Arguments = argument;            startInfo.CreateNoWindow = true;            startInfo.UseShellExecute = false;            startInfo.RedirectStandardInput = true;            startInfo.RedirectStandardOutput = true;            startInfo.RedirectStandardError = true;            exep.StartInfo = startInfo;            exep.Start();            exep.WaitForExit();        }        return savePath;    }}

  

// This file is NOT a browser-run javascript but PhantonJS scriptvar system = require(‘system‘);var address = system.args[1];var output = system.args[2];var page = require(‘webpage‘).create();page.paperSize = {  format: ‘A4‘,  orientation: ‘landscape‘,  border: ‘1cm‘};page.open(address, function (status) {    if (status !== ‘success‘) {        console.log(‘Unable to load the address!‘);        phantom.exit();    } else {        window.setTimeout(function () {            // Remove all low-opacity paths. see PhantomJS  issue #364             page.evaluate(function () {                var paths = document.getElementsByTagName("path");                for (var i = paths.length - 1; i >= 0; i--) {                    var path = paths[i];                    var strokeOpacity = path.getAttribute(‘stroke-opacity‘);                    if (strokeOpacity != null && strokeOpacity < 0.2)                        path.parentNode.removeChild(path);                }            });            page.render(output);            phantom.exit();        }, 5000);    }});

  

開篇

最近使用 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

}
});
}

 1 var page = require(‘webpage‘).create(), 2     system = require(‘system‘), 3     address, output, size; 4  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     phantom.exit(1); 9 } else {10     address = system.args[1];11     output = system.args[2];12     /*size of browser*/13     page.viewportSize = { width: 600, height: 600 };14     /*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: ‘A4‘, orientation: ‘portrait‘, margin: ‘1cm‘ };19     }20     */21     /* ie and chrome view diffrent format of pdf */22     page.settings.userAgent = ‘Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36‘;23     page.paperSize = { format: ‘A4‘, orientation: ‘portrait‘, margin: ‘0.8cm‘ };24     page.zoomFactor = 1;25     page.settings.loadImages = true;26     //some question about the page language27     page.open(address, function (status) {28         if (status !== ‘success‘) {29             console.log(‘Unable to load the address!‘);30         } else {31             //page.render(output);32             //phantom.exit();33             34             window.setTimeout(function () {35                 page.render(output);36                 phantom.exit();37             }, 200); //setting the time is enough to loading the page. document.ready38             39         }40     });41 }

 

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)設定,頁面使用樣式即可:

1 style = “page-break-after: always;”

控制每頁內容的大小,使用 <div style="page-break-after: always;">content</div> 就行。

更多選擇 style=“page-break-before: always;” , style="page-break-inside: avoid;" 這個可以避免內容散到兩頁中

 

phantomjs html to PDF

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.