4

我想知道是否有办法在执行 pdf copnversions 时避免保存物理文件。我正在运行 PhantomJS 作为 pdf 转换的服务器,并且希望避免存储物理文件的后勤工作。

在 API 中,我看到了render(filename)需要文件名并将转换结果写入文件系统的方法。

我想我正在寻找的是类似renderBase64(format)返回 base 64 编码缓冲区的东西。遗憾的是,这种方法不支持 pdf - 仅支持图像格式。

转换pdf时有没有办法避免文件保存?

我希望服务的消费者(其他浏览器)处理文件保存

4

1 回答 1

2

你说得对:保存 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" +
              "wxyz0123456789+/" +
              "=";

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 编码器。

于 2013-07-08T07:16:14.770 回答