你是正確的:保存PDF的唯一方法需要一個文件名。我不認爲有計劃爲下一個版本改變這一點。
爲避免物理存儲物理文件,你只需要一個工作目錄。將pdf保存到臨時文件並刪除一次。
一個非常基本的腳本可以
var page = require('webpage').create(),
system = require('system');
var fs = require('fs');
var Guid = function() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
// then to call it, plus stitch in '4' in the third group
return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0, 3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
}
var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz/" +
"=";
function encode64(input) {
input = escape(input);
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
if (system.args.length != 2) {
console.log('Usage: printer.js URL');
phantom.exit(1);
} else {
var address = system.args[1];
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
//create temporary file (current dir)
var tmpfileName = Guid() + '.pdf';
//render page
page.render(tmpfileName);
//read tmp file + convert to base64
var content = encode64(fs.read(tmpfileName));
//send (or log)
console.log(content);
//delete
fs.remove(tmpfileName);
phantom.exit();
}
});
}
我在這裏使用一個GUID功能(生成隨機文件名)和一個JS的Base64編碼器。
謝謝。我覺得是這樣 – TGH